Question about "in place" operations

Hello,
At the moment I’m studying a little bit of code optimisation. I don’t understand why in case with sample() we have 16 bytes allocated and in the second case 0 (with the in place operation “sample!()”). Isn’t it possible to change the value of a float or an int without reallocating memory? Do you have to use a single-value vector to do this?

Thank you!
fdekerm

julia> using StatsBase

julia> x = [0.0]
1-element Vector{Float64}:
 0.0

julia> y = rand(10)
10-element Vector{Float64}:
 0.711827244320969
 0.748420926219918
 0.3664891177657702
 0.787337039347841
 0.25127202582425534
 0.02232231788819372
 0.5835537053001686
 0.5261181974982757
 0.6587823584053296
 0.16470270236878148

julia> z = 0.0
0.0

julia> @allocated z = sample(x)
16

julia> @allocated sample!(x,y)
0

That’s just an artifact of the benchmark:

julia> using BenchmarkTools

julia> y = rand(10);

julia> @ballocated z = sample($y)
0
3 Likes