piever
August 7, 2026, 1:33pm
21
rokke:
I usually use reduce(∘, repeated(func, x))(a) when I need to apply func to a x times, but apparently it spends most of the time creating the single composed function; […] is there a way to tell julia to just apply the functions directly instead of first collecting them into a composed function?
A bit late to the party, but the closest thing to what you are doing is to use foldl with |> instead of creating the composite function. For instance
val = 1.2
n = 5
foldl(|>, Iterators.repeated(exp, n), init = val)
I haven’t benchmarked it, but I’ve found foldl(|>, fs, init = val) to be a pretty useful pattern to compose a list of functions, but of course the other approach with (y, _) -> exp(y) also works if all the functions are equal.
rokke
August 7, 2026, 1:44pm
22
nice, looks like that’s basically the same as the other best ones and is much easier to read:
master:
julia> f(a) = foldl(|>, repeated(exp, 1000); init=a)
f (generic function with 3 methods)
julia> @benchmark f(10.)
BenchmarkTools.Trial: 10000 samples with 999 evaluations per sample.
Range (min … max): 8.245 ns … 184.536 ns ┊ GC (min … max): 0.00% … 0.00%
Time (median): 9.232 ns ┊ GC (median): 0.00%
Time (mean ± σ): 9.830 ns ± 3.589 ns ┊ GC (mean ± σ): 0.00% ± 0.00%
▃ ▄▇█▇▃ ▅▃ ▂▁ ▂
█▆▄▄██████▇▆▆▄▄▄▆▄███▇▇▆██▇▆▆▆▆▆▆▆▆▆▆▅▆▇▆▇▇▆▆▆▅▅▅▆▆▆▄▅▄▄▅▄▅ █
8.25 ns Histogram: log(frequency) by time 16.7 ns <
Memory estimate: 0 bytes, allocs estimate: 0.
julia> @benchmark f($10.)
BenchmarkTools.Trial: 10000 samples with 5 evaluations per sample.
Range (min … max): 5.883 μs … 112.796 μs ┊ GC (min … max): 0.00% … 0.00%
Time (median): 7.540 μs ┊ GC (median): 0.00%
Time (mean ± σ): 7.786 μs ± 2.355 μs ┊ GC (mean ± σ): 0.00% ± 0.00%
▂ ▅▅ █▂ ▁▁ ▂▁ ▁
█▅▂██▇▆▇██▇███████▇▇▇▆▆▆▆▄▅▅▅▆▆▅▆██▆▅▅▅▅▃▄▅▅▆▄▃▂▃▂▅▃▃▃▂▂▃▃▅ █
5.88 μs Histogram: log(frequency) by time 17.1 μs <
Memory estimate: 0 bytes, allocs estimate: 0.