Search code examples
performancerustperformance-testingrust-macros

Is there any performance difference between macros and functions in Rust?


In Rust Macros are executed at compile time. They generally expand into new pieces of code that the compiler will then need to further process.

But after macros compiled or before compiled is there any performance difference between normal function vs macros?


Solution

  • I assume you're talking about runtime performance. Compile-time wise macros are usually slower as they are compiled for each invocation.

    Macros are like #[inline(always)] functions. This can be good or bad for performance, depending on lot of characteristics like number of calls to the code, code size or instruction cache pressure. Always benchmark before making a decision.

    If you can use a function, prefer that. It can always be marked #[inline(always)] if deemed good for performance, while using more familiar syntax and faster compile times.