Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia: Are nested functions slower?

When I write a code, and I can see repeat parts in a function but aren't used in the other functions.

So, I want to make repeat part to function.

But are nested functions slower? I couldn't find this in Performance tip in julia docs.

like image 951
kn05 Avatar asked Oct 24 '25 14:10

kn05


1 Answers

The question has been generally answered by Bogumil in the comment. Just to realize that inlining works you can do this small experiment. Define the following f and g functions.

f(x) = x*x

function g(a,b)
  a+f(b)
end

Now let's see what compiler does with them:

julia> @code_typed g(3,4)
CodeInfo(
1 ─ %1 = Base.mul_int(b, b)::Int64
│   %2 = Base.add_int(a, %1)::Int64
└──      return %2
) => Int64

You can see that the call to the function f has been inlined.

Generally small functions will be inlined, the larger ones can be decorated with the @inline macro to suggest the compiler in-lining (note that this is only a hint). Since the cost of calling a function is small when it has more than just a few lines of code, calling it does not affect performance in a significant way.

Last but not least doing your own benchmark with BenchmarkTools seems always like a good idea :-)

like image 96
Przemyslaw Szufel Avatar answered Oct 28 '25 05:10

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!