How to avoid memory allocation when having long expression

julia> using FastBroadcast, BenchmarkHistograms

julia> dTA_dH = zeros(100);

julia> H = zeros(100);

julia> const ⊕ = +
+ (generic function with 378 methods)

julia> const ⊗ = *
* (generic function with 590 methods)

julia> function test(dTA_dH, H)
           @.. dTA_dH +=
               -1.0 ⊗ 1.0 ⊗ 1.0 ⊗ (2 ⊗ H^3 ⊕ H^2 ⊗ 1.0 - 1.0 ⊗ 1.0 ⊗ 1.0) /
               (H^3 ⊕ H^2 ⊗ 1.0 ⊕ H ⊗ 1.0 ⊗ 1.0 ⊕ 1.0 ⊗ 1.0 ⊗ 1.0)^2
       end
test (generic function with 1 method)

julia> @benchmark test($dTA_dH, $H)
samples: 10000; evals/sample: 967; memory estimate: 0 bytes; allocs estimate: 0
ns

 (81.75 - 82.04 ]  ██████████████████████████████ 9191
 (82.04 - 82.33 ]   0
 (82.33 - 82.62 ]  ▏1
 (82.62 - 82.91 ]  ▌124
 (82.91 - 83.2  ]  ██600
 (83.2  - 83.49 ]  ▎48
 (83.49 - 83.78 ]  ▏18
 (83.78 - 84.07 ]  ▏1
 (84.07 - 84.36 ]  ▏1
 (84.36 - 84.65 ]  ▏2
 (84.65 - 84.94 ]  ▏1
 (84.94 - 85.23 ]  ▏1
 (85.23 - 85.52 ]   0
 (85.52 - 85.81 ]  ▏2
 (85.81 - 124.26]  ▏10

                  Counts

min: 81.751 ns (0.00% GC); mean: 81.943 ns (0.00% GC); median: 81.840 ns (0.00% GC); max: 124.259 ns (0.00% GC).

Note the extra . in @.. from FastBroadcast.jl.

4 Likes