Are anonymous functions efficient in allocation terms?

Simple question:
As a little step in a function I’m working on, I need to filter a unit range, say 1:5, just by taking one of its elements away, say 2. I understand that filter() is the way to go, combined with an anonymous function this way:

@time filter(x -> x .!=2, 1:5)

I’ve tried that several times with the time macro and each time it makes 88.81 K allocations, which is simply a lot, I would say. I also tried a similar filtration not using an anonymous function:

@time filter(isodd,1:5)

Just 14 allocations! I know I just tried 2 different cases, but I’m tempted to think that anonymous functions are very inefficient? I’m working on an MCMC algorithm, so if I’m repeating this step thousands of times, it’ll take days or my laptop is just going to crash.

Any suggestions on how to make this simple filtering efficiently are highly appreciated.

Cheers.

R.

You’re creating a new closure every time you’re timing it, so you’re benchmarking compilation time for that new closure. If you put it in a separate function (i.e. reusing the old closure type, you can see the effect):

julia> f(x) = filter(x -> x .!=2, x)
f (generic function with 2 methods)

julia> @time f(1:5)
  0.034321 seconds (54.73 k allocations: 2.819 MiB)
4-element Array{Int64,1}:
 1
 3
 4
 5

julia> @time f(1:5)
  0.000005 seconds (8 allocations: 448 bytes)
4-element Array{Int64,1}:
 1
 3
 4
 5
5 Likes

Try using BenchmarkTools

julia> using BenchmarkTools
julia> @btime filter(x -> x .!=2, 1:5)
  211.729 ns (7 allocations: 352 bytes)
4-element Array{Int64,1}:
 1
 3
 4
 5

julia> @btime filter(isodd, 1:5)
  207.497 ns (7 allocations: 352 bytes)
3-element Array{Int64,1}:
 1
 3
 5
2 Likes

Thanks a lot! I’ll do that.

Thanks a lot!