As the title says, is there a way to pass an immutable into a function, have it allowed to be mutated, but make it have low overhead? It seems like wrapping it in some reference makes it about >2x slower:
using BenchmarkTools
a = Array{Float64}()
a[] = 1.0
function test_dim0_array(a)
for i = 1:1000
a[] += rand()
end
end
test_dim0_array(a)
@benchmark test_dim0_array($a)
BenchmarkTools.Trial:
memory estimate: 0.00 bytes
allocs estimate: 0
--------------
minimum time: 3.074 μs (0.00% GC)
median time: 3.220 μs (0.00% GC)
mean time: 3.610 μs (0.00% GC)
maximum time: 28.469 μs (0.00% GC)
--------------
samples: 10000
evals/sample: 8
time tolerance: 5.00%
memory tolerance: 1.00%
a = Ref{Float64}()
a[] = 1.0
@benchmark test_dim0_array($a)
BenchmarkTools.Trial:
memory estimate: 0.00 bytes
allocs estimate: 0
--------------
minimum time: 2.374 μs (0.00% GC)
median time: 2.472 μs (0.00% GC)
mean time: 2.651 μs (0.00% GC)
maximum time: 16.068 μs (0.00% GC)
--------------
samples: 10000
evals/sample: 9
time tolerance: 5.00%
memory tolerance: 1.00%
type Container
a::Float64
end
a = Container(1.0)
function test_container(a)
for i = 1:1000
a.a += rand()
end
end
test_container(a)
@benchmark test_container($a)
BenchmarkTools.Trial:
memory estimate: 0.00 bytes
allocs estimate: 0
--------------
minimum time: 2.374 μs (0.00% GC)
median time: 2.537 μs (0.00% GC)
mean time: 2.747 μs (0.00% GC)
maximum time: 12.490 μs (0.00% GC)
--------------
samples: 10000
evals/sample: 9
time tolerance: 5.00%
memory tolerance: 1.00%
For comparison, here it is just using the number:
function test_num(a)
for i = 1:1000
a += rand()
end
end
test_num(1.0)
@benchmark test_num(1.0)
BenchmarkTools.Trial:
memory estimate: 0.00 bytes
allocs estimate: 0
--------------
minimum time: 1.288 μs (0.00% GC)
median time: 1.347 μs (0.00% GC)
mean time: 1.479 μs (0.00% GC)
maximum time: 12.149 μs (0.00% GC)
--------------
samples: 10000
evals/sample: 10
time tolerance: 5.00%
memory tolerance: 1.00%
Is there something better than using a Ref
, or is this as good as it gets?