deepcopy
is generally slower for arrays than creating a new array and copying the data from the old array, so why would I every use it then? deepcopy
creates an ObjectIdDict
internally which probably causes the main performance overhead.
julia> using BenchmarkTools
julia> f(x) = deepcopy(x)
f (generic function with 1 method)
julia> function g(x::Array{T}) where T
y = Array{T}(undef, length(x))
copyto!(y, x)
end
g (generic function with 2 methods)
julia> x = collect(1:100);
julia> @benchmark f($x)
BenchmarkTools.Trial:
memory estimate: 1.30 KiB
allocs estimate: 3
--------------
minimum time: 201.290 ns (0.00% GC)
median time: 220.049 ns (0.00% GC)
mean time: 269.109 ns (13.64% GC)
maximum time: 63.888 μs (99.18% GC)
--------------
samples: 10000
evals/sample: 606
julia> @benchmark g($x)
BenchmarkTools.Trial:
memory estimate: 896 bytes
allocs estimate: 1
--------------
minimum time: 106.996 ns (0.00% GC)
median time: 124.724 ns (0.00% GC)
mean time: 150.505 ns (13.92% GC)
maximum time: 41.561 μs (99.36% GC)
--------------
samples: 10000
evals/sample: 935
To put it simply though, if you don’t know why you should use deepcopy, that’s likely not the function you want. It’s not a function to use in most cases.
For me the main usage is to copy an array, and as it is the simplest way to do so provided by the language, I also expected it to be the fastest. I did not expect deepcopy
to be the performance bottleneck which caused some confusion.
EDIT: added note about ObjectIdDict
EDIT: added response to @yuyichao’s comment on github