Hello all,
I'm running into some unexpected memory allocations that I'm hoping someone
can help me with. Here's an example the demonstrates the problem:
function sum_rand(n::Int)
s = zero(Float64)
for i in 1:n
s += rand(Float64)
end
return s
end
sum_rand(x::Vector) = sum_rand(length(x))
function sum_vector{T}(x::Vector{T})
s = zero(T)
for i in 1:length(x)
s += x[i]
end
return s
end
x = rand(100);
@allocated sum_rand(100) # 0
@allocated sum_rand(length(x)) # 16
@allocated sum_rand(length(x)::Int) # 0
@allocated sum_rand(x) # 16
@allocated sum_vector(x) # 16
For some reason adding values that are read from an array allocates memory
for the accumulating variable while summing up random values does not.I
would have thought that the accumulating variable would be stack allocated
for both functions. It's not a lot of memory per function call, but I have
code that sums up arrays in an inner loop, so the total cost adds up.
Any suggestions?
Thanks,
Darwin