In the functions sections of the language reference there’s an example of inlining a function using callconv(.Inline)
. I’ve also seen inline fn
used in existing Zig code.
- Is there a difference?
- Is one preferred over the other?
- Is it really necessary or is it best to let the compiler decide when to inline a function?
2 Likes
No, there seems to be no difference.
- Is one preferred over the other?
I prefer using inline fn
because I think it’s more readable.
It also seems to be the preferred version in the compiler source code and standard library.
There is over 400 uses of inline fn
and only 4 uses of callconv(.Inline)
- Is it really necessary or is it best to let the compiler decide when to inline a function?
Generally the llvm optimizer is pretty good at inlining functions.
However manual function inlining is already happening in semantic analysis and is independant of the build mode.
So manual inlining can improve runtime of debug builds.
Additionally it might improve compile-time if the function is small enough or only used once.
However I would recommend to only manually inline if you have a good reason. But generally I guess it wouldn’t hurt to mark tiny functions as inline
By the way there is also a third way to inline functions using
@call(.always_inline, function, parameterTuple);
This allows you to decide at the callsite whether a function should be inlined.
5 Likes
It’s best to let the compiler decide when to inline a function, except for these scenarios:
- You want to change how many stack frames are in the call stack, for debugging purposes
- You want the comptime-ness of the arguments to propagate to the return value of the function
- Performance measurements demand it. Don’t guess!
Otherwise you actually end up restricting what the compiler is allowed to do when you use inline
which can harm binary size, compilation speed, and even runtime performance.
6 Likes
I only inline functions if they consist of mostly inline assembly or if they’re really small and are things like just a single return statement that computes a value. Otherwise I try to avoid inlining. I’d say that’s typically good advice generally.