It looks like the type inference is failing in version1. If you do 
"@code_warntype version1(1000)", it shows that it is inferring the type of 
b as Any.

On Thursday, April 21, 2016 at 11:32:27 AM UTC-6, Jeremy Kozdon wrote:
>
> In a class I'm teaching the students are using Julia and I couldn't for 
> the life of me figure out why one of my students codes was allocating a lot 
> of memory.
>
> I finally paired it down the following example that I don't understand:
>
> function version1(N)
>   b = [1;zeros(N-1)]
>   println(typeof(b))
>   for k = 1:N
>     for j = 1:N
>       b[j] += k
>     end
>   end
> end
>
>
> function version2(N)
>   b = zeros(N)
>   b[1] = 1
>   println(typeof(b))
>   for k = 1:N
>     for j = 1:N
>       b[j] += k
>     end
>   end
> end
>
> N = 1000
> println("compiling..")
> @time version1(N)
> version2(N)
> println()
> println()
>
> println("Version 1")
> @time version1(N)
> println()
>
> println("Version 2")
> @time version2(N)
>
> The output of this (without the compiling output) in v0.4.5 is:
>
> Version 1
> Array{Float64,1}
>   0.092473 seconds (3.47 M allocations: 52.920 MB, 3.24% gc time)
>
> Version 2
> Array{Float64,1}
>   0.001195 seconds (27 allocations: 8.828 KB)
>
> Both version produce the same type for Array b, but in version1 every time 
> through the loop allocation happens and in the version2 the only allocation 
> is of the initial array.
>
> I've not run into this one before (because I would never do version1), but 
> as all of us that teach know students will always surprise you with their 
> approaches.
>
> Any help understanding what's going on would be appreciated.
>

Reply via email to