Allocation seem high for such a simple function?

minimumby(f, itr) = itr[argmin(map(f, itr))]
@time minimumby(x->x^2, [-2, 1, 2, 3, 4])

I get

 0.044858 seconds (48.96 k allocations: 2.505 MiB)

This is quite slow and a lot of allocations

But if I give the function a name then it’s fast

f(x) = x^2

@time minimumby(f, [-2, 1, 2, 3, 4])
0.000009 seconds (3 allocations: 272 bytes)

Wondering why can’t Julia just “compile” the anonymous function away ?

1 Like

Because you are just observing the anonymous function being compiled away. Your x->x^2 create a new function everytime you typed that in.

I see. I thought it would hash the code and see thst it’s not new or something