Boxing of integer when looping vector over 512 index

Weird allocation that depends on array contents · Issue #36751 · JuliaLang/julia · GitHub & memory allocation increases unexpectedly in sparse getindex at a threshold · Issue #18051 · JuliaLang/julia · GitHub mention llvm caching of integer boxing between -512 & 512.
However, I don’t understand why we need boxing. Is there any way to avoid it? It looks like they managed it here memory allocation increases unexpectedly in sparse getindex at a threshold · Issue #18051 · JuliaLang/julia · GitHub

v=Vector{Int64}(undef, 1000)

julia> @time for i in 510:511 v[i]=3 end
  0.000002 seconds

julia> @time for i in 511:512 v[i]=3 end
  0.000002 seconds (1 allocation: 16 bytes)

Because you are in global scope. Put it in a function and it will not allocate.

1 Like

:man_facepalming: you’re right, noob question. thanks!

2 Likes