You can do something like:
julia> my_rates_buffer = zeros(1001)
julia> function custom_test!(rates, data::Vector{Float64}, i::Int64)
if(i < 1001)
return nothing
end
copyto!(rates, @view data[i-1000:i])
return nothing
end
custom_test! (generic function with 1 method)
julia> @time custom_test!(my_rates_buffer, my_test, 5000) # Only first use, no problem at all.
0.076472 seconds (112.11 k allocations: 5.599 MiB, 99.96% compilation time)
julia> @time custom_test!(my_rates_buffer, my_test, 5000)
0.000009 seconds
Now there’s no allocation, but still a copy, despite that @view
. You need it otherwise you get two allocations (I believe 1 more since 1.11). copyto! returns something, and without that return nothing
after it would be returned. If comment it out I get it, and still no allocation. I think it’s then returning the view (i.e. without that it will allocate, not more though). I mainly include it in to not return either nothing or the view, but that type stability seems to cost you nothing (probably unless you use that result?).
Before in your code, you did malloc
implicitly, as in C++ (new
in C++ needs not actually call malloc
according to the C++ standard, though in practice it’s always implemented that way; your “new” is implicit, also, comes from invoking std::vector
).
That malloc isn’t any slower in Julia (maybe even faster…). Not in Julia you’re allocating a lot (and copying to that memory buffer that’s never in the same place since the previous wasn’t yet released), i.e.:
julia> @time for i in 1:10000 Libc.malloc(200) end
0.000889 seconds
julia> @time for i in 1:10000 b = Libc.malloc(200); Libc.free(b) end
0.000201 seconds
Julia could do effectively the latter, like in C++. And add your code in-between. But at least freeing (the most recent allocation) makes malloc (in Libc) faster.
With Bumper.jl or something you can in effect do the latter, except it’s even faster “malloc” and “free”, since not really done at all. Something in Julia that does implicit free is coming, i.e. allocating on the stack when possible, for such no cost, when it can apply.