Performance of functions with keyword arguments


#1

In the manual, we read:

Functions with keyword arguments have near-zero overhead for call sites that pass only positional arguments.

Does this mean that functions with keyword arguments are as fast as functions without keyword arguments as long as they don’t use any keyword arguments? Or that keyword arguments don’t affect performance if there are no optional arguments?

An example might help me understand this… :slight_smile:


#2

might want to edit the title :smiley:


#3

Perhaps:

julia> f_kw(x; y = 3) = x + y
f_kw (generic function with 1 method)

julia> f(x, y = 3) = x + y
f (generic function with 2 methods)

julia> @btime f_kw(2);
  1.789 ns (0 allocations: 0 bytes)

julia> @btime f_kw(2, y = 3);
  66.668 ns (1 allocation: 96 bytes)

julia> @btime f(2);
  1.789 ns (0 allocations: 0 bytes)

#4

Thanks! So, functions with keyword arguments are slower if you actually use the keyword arguments… This seems a bit disappointing (?); perhaps I’ve over-used them in the past, and should think about other techniques for specifying options…


#5

Yes. Essentially they cannot be inferred in the current setup, so keyword arguments actually have a dynamic dispatching function barrier in there which adds the cost. You can see this in action if you @code_typed and see that you don’t get back your real function and instead get back a function which calls an internal function. This will be changed when NamedTuples are in Base because then it will be able to infer.


#6

Cool, thanks. So if I wait (till 0.7)? I don’t have to work out an alternative to keyword arguments. Sounds like a plan.


#7

Yeah, it seems like it’s v0.7 which will have it. I stopped worrying about this awhile ago: Julia moves fast enough that you can just program for the future Julia instead of spending time with current limitations.