Inline macro

When should I use the @inline macro to optimize performance?

TLDR: for short functions where it will be faster if the compiler to “copy-paste” the definition of the function into it’s caller instead of making a function call. That said, the compiler generally does a pretty good job of doing this on its own, so I wouldn’t worry about it much if you are relatively new to Julia. It is generally a fairly minor factor.

2 Likes

Off topic, I’m curious about how one can define an inline function without using any macro? Following the result of @macroexpand(@inline f(x) = x), I came up with

eval(quote
   f(x) = begin
       $(Expr(:meta, :inline))
       x
   end
end)

But this looks crazy. Is there a better way?

1 Like

This one is easy. Just

eval(quote
   @inline f(x) = begin
       x
   end
end)
1 Like

Can you do it without using any @ character in the code? That was what I wanted to find out (again, just for curiosity).

I don’t think so, but also why?

Actually I’m just trying to learn the basics of macros, by reading the expanded code of all sorts of built-in macros like @inline and @enum. I’m a bit surprised that there are things like Expr(:meta, ...) and Exp(:toplevel, ...), which cannot be easily written down as “normal” Julia code. Macros written down by a beginner like me can always be replaced by normal-looking explicit code, so I’m trying to understand why the built-in macros have more magic in them.

1 Like

That makes sense. The basic answer is that Base needs some functionality that requires custom support from the language. In these cases, the typical approach is to add something to Julia’s AST syntax, and make a macro that inserts that type of AST node as a fron-end to the compiler internals.

In effect, the causality is backwards. It’s not that Base implements lots of built-in macros, it’s that if you want a built-in macro, it has to live in Base.

Also, @enum isn’t special. You could implement it yourself if you wanted, it’s just a little complicated.

3 Likes