Unless you make the globals `const`, the compiler doesn't know the type of 
globals, so every single access to it must be "interpreted", so to speak. 
There are talks of adding a way to specify the type of globals, that would 
give them comparable speed to function arguments.

On Saturday, September 19, 2015 at 8:14:19 PM UTC-4, Eric Forgy wrote:
>
> On Sunday, September 20, 2015 at 2:16:07 AM UTC+8, David Gold wrote:
>>
>> One thing I suspect is hurting you is that you're storing your parameters 
>> in a `Dict` object. Because the parameters are all of different types, (and 
>> because of the way you declare the `Dict`), they are stored in a `Dict{Any, 
>> Any}`, which means that Julia's type inference system is unable to discern 
>> at JIT-compilation time what the result of indexing into your `param` 
>> object will be. The result is that the emitted code must box everything 
>> that comes out of `param`, making everything that touches `param` allocate 
>> memory and incur a performance penalty. This would be consistent with your 
>> observation that removing type annotations worsens performance, since type 
>> annotations shouldn't matter when Julia's compiler can infer the types of 
>> objects passed around. Furthermore, since you set a number of loop bounds 
>> with values from `param`, I suspect that the type-uncertainty here hinders 
>> any optimization effort to remove bounds checks in those loops.
>>
>> Try instead storing your parameters in a custom immutable type:
>>
>> immutable Parameters
>>     D::Int
>>     T::Int
>>     I::Int
>>     max_b::Int
>>     w_max::Int
>>     gamma::Float64
>>     controls::Vector{Float64}
>>     num_controls::Int
>>     o_vec::Array{Int, 2}
>> end
>>
>> You can then initialize a Parameters object such as `param = Parameters( 
>> ... )` and replace all dict indexing with field access. Do the same for 
>> `dist` and `data`. (You may not be able to make these immutable, though, 
>> depending on whether or not you need to update them).
>>
>> Finally, I'd wrap your `v1`, `term_condition` and `iter` declarations, as 
>> well as the subsequent `while` loop, in a `run()` function.
>>
>
> This is great advice. Thanks David. Coming from Matlab, I am making the 
> same mistakes with Dict{Any,Any} in my code. I'll try immutable parameters 
> and maybe have a go at adding this wisdom to "Performance Tips".
>
> Is it correct to say that the warnings about global variables are 
> effectively warnings about "Any"? We should avoid anything that ends up 
> with "Any"? I think this is implied in the tips, but making it more 
> explicit might help. We have two data points here of Matlabers making the 
> same mistake in Julia and there must be others.
>

Reply via email to