Here are some benchmarks for computing this with:
- map:
map(area, triangles)
- comprehension: `[area(triangle) for triangle in triangles]
- broadcasting:
area.(triangles)
using interpolation $ on the non-local global variable triangles (based on @DNF comment).
Definitions
using Pkg
Pkg.add("BenchmarkTools")
using BenchmarkTools
struct Triangle
height::Float64
base::Float64
end
function area(t::Triangle)
0.5 * t.height * t.base
end
triangles = [Triangle(rand(), rand()) for _ in 1:1000000]
Results
julia> @benchmark map(area, $triangles)
BenchmarkTools.Trial:
memory estimate: 7.63 MiB
allocs estimate: 3
--------------
minimum time: 1.168 ms (0.00% GC)
median time: 2.510 ms (0.00% GC)
mean time: 2.485 ms (10.00% GC)
maximum time: 43.540 ms (91.62% GC)
--------------
samples: 2008
evals/sample: 1
julia> @benchmark [area(triangle) for triangle in $triangles]
BenchmarkTools.Trial:
memory estimate: 7.63 MiB
allocs estimate: 3
--------------
minimum time: 1.150 ms (0.00% GC)
median time: 1.921 ms (0.00% GC)
mean time: 2.327 ms (10.76% GC)
maximum time: 45.883 ms (91.42% GC)
--------------
samples: 2144
evals/sample: 1
julia> @benchmark area.($triangles)
BenchmarkTools.Trial:
memory estimate: 7.63 MiB
allocs estimate: 2
--------------
minimum time: 1.165 ms (0.00% GC)
median time: 1.224 ms (0.00% GC)
mean time: 1.961 ms (10.13% GC)
maximum time: 44.156 ms (89.33% GC)
--------------
samples: 2544
evals/sample: 1
This would indicate that for this input size, the broadcasting method seems to be the fastest.
For different input size, relative timings may be different, so it is probably a good idea to benchmark it yourself for your use case