I think you can use resize! and then normal setindex syntax instead of push, which has more complex logic (because you deliberately set the hinted size, which push doesn’t know and has to check every time)
Additionally, earlier version of foo was a bit too simplistic. I don’t really know the new buffer size at the beginning as it suggested. This is closer to the reality of my algorithm:
function foo(buf)
empty!(buf)
while length(buf) < rand(1:n)
push!(buf, rand(1:n))
end
end
Now I’m scratching my head trying to figure out why… Is there any other reason for compiler to call allocate than pushing to array, which already used all preallocated memory?
Another option to avoid allocation is to parametrize foo with n:
function foo(buf, n)
empty!(buf)
while length(buf) < rand(1:n)
push!(buf, rand(1:n))
end
end
Is the compiler trying to be too smart for its own good?
I think the problem is that if n is a global and not a const, the getnum function is not guaranteed to return an int because it needs to be prepared for n to be mutated to anything else. That’s why getnum is not type stable and to deal with that some helper data structures that cause allocations are needed
My point is that foo and bar can be executed without needing allocations. Why is that for some external conditions compiler produces allocations and for others it doesn’t? The control and data flow are identical with and without allocations.
Also:
n = 9
function baz()
println(typeof(rand(1:n)))
end
julia> baz()
Int64
I meant, why compiler analysis of getnum() determines whether allocation will be performed? I see that unknown return type of getnum as mentioned by @jules could necessitate that, but it is not the case, is it?
What you did there with the typeof does nothing for checking type stability. Use @code_warntype. Also, a type assert doesn’t help with the fact that n is a global that you use.
It really seems you should read Performance Tips · The Julia Language carefully. Counting the exact number of allocations in type unstable code is pretty pointless, it’s mostly counting implementaion details.