Archive

Ineffective Theory

A note on macro performance in Julia

At least in Julia 1.10 (also 1.9), macros are not compiled. That means that

macro m()
    for i in 1:1000000
        # do something
    end
end

@m

can be quite slow. This is analogous to how running code directly from a script, instead of creating a function main() and calling that function at top-level, is not advised. Only code in functions is compiled/optimized, and macros do not count as functions.

All is not lost; in fact very little is lost. Functions are of course compiled, and functions can be called from macros. Therefore this is fast:

function mfunc()
    for i in 1:1000000
        # do something
    end
end

macro m()
    mfunc()
end

@m

Functions can return Expr objects as well, so even if a macro is slow entirely from AST manipulations, it can be optimized by offloading that work into a function.