[julia-users] Array element assignment in for loop

2015-11-25 Thread Kristoffer Carlsson
Return k from the first function and you will see that things change.

If you make a function that actually doesn't do anything, you shouldn't be 
surprised if the compiler gives you a function that doesn't do anything. :)

[julia-users] Array element assignment in for loop

2015-11-25 Thread Paul Thompson
Hi:

I've noticed that there is a performance cost associated with assigning a 
value to an array in a loop, compared to just using it for calculation. 
Here are some examples to demonstrate:

function mytest(a::Array{Float64,1},b::Array{Float64,1})
k=0.0
for i=1:length(a)
@inbounds k+=b[i]
end

nothing 
end

function mytest2(a::Array{Float64,1},b::Array{Float64,1})

for i=1:length(a)
@inbounds a[i]+=b[i]
end

nothing 
end

function mytest3(a::Array{Float64,1},b::Array{Float64,1})

for i=1:length(a)
@inbounds a[1]+=b[i]
end

nothing 
end

function mytest4(a::Array{Float64,1},b::Array{Float64,1})
   
for i=1:length(a)
@inbounds setindex!(a,b[i]+a[i],i)
end

nothing

end

c=rand(Float64,10); d=rand(Float64,10);

@time mytest(c,d);
@time mytest2(c,d);
@time mytest3(c,d);
@time mytest4(c,d);

0.03 seconds (4 allocations: 160 bytes)
0.000164 seconds (4 allocations: 160 bytes)
0.000183 seconds (4 allocations: 160 bytes)
0.000139 seconds (4 allocations: 160 bytes)


At first, I thought that just accessing array was more expensive than a 
single variable like k in the first example, but using the value of b[i] at 
each iteration doesn't seem to have much overhead. I expect that the 
difference between mytest2 and mytest3 is because of some caching issue 
under the hood since the beginning of one array is repeatedly indexed, 
while the location in the second array changes. I'm not sure why using 
setindex! is faster than bracketed indexes.

Anyone have any ideas of what is going on here? It is still super fast, but 
in some performance critical code where I am making multiple array 
assignments per iteration, I wouldn't mind find avoiding the expense above 
if I can.

Thanks!

Paul