@always_inline
You can add the @always_inline
decorator on any function to make the Mojo compiler “inline” the body of the function (copy it) directly into the body of the calling function.
This eliminates potential performance costs associated with function calls jumping to a new point in code. Normally, the compiler will do this automatically where it can improve performance, but this decorator forces it to do so. The downside is that it can increase the binary size by duplicating the function at every call site.
For example:
@always_inlinefn add(a: Int, b: Int) -> Int: return a + bprint(add(1, 2))
Because add()
is decorated with @always_inline
, Mojo compiles this program without adding the add()
function to the call stack, and it instead performs the addition directly at the print()
call site, as if it were written like this:
print(1 + 2)
@always_inline("nodebug")
You can also use the decorator with the "nodebug"
argument, which has the same effect to inline the function, but without debug information. This means you can’t step into the function when debugging, but it reduces the debug build binary size.
@nonmaterializable
You can add the @nonmaterializable
decorator on a struct to declare that the type can exist only in the parameter domain (it can be used for metaprogramming only, and not as a runtime type). And, if an instance of this type does transition into the runtime domain, this decorator declares what type it becomes there.
To use it, declare your type with @nonmaterializable(TargetType)
, where TargetType
is the type that the object should convert to if it becomes a runtime value (you must declare the TargetType
). For example, if a struct is marked as @nonmaterializable(Foo)
, then anywhere that it goes from a parameter value to a runtime value, it automatically converts into the Foo
type.
For example, the following NmStruct
type can be used in the parameter domain, but the converted_to_has_bool
instance of it is converted to HasBool
when it’s materialized as a runtime value:
@value@register_passable("trivial")struct HasBool: var x: Bool fn __init__(x: Bool) -> Self: return Self {x: x} @always_inline("nodebug") fn __init__(nms: NmStruct) -> Self: return Self {x: True if (nms.x == 77) else False}@value@nonmaterializable(HasBool)@register_passable("trivial")struct NmStruct: var x: Int @always_inline("nodebug") fn __add__(self: Self, rhs: Self) -> Self: return NmStruct(self.x + rhs.x)alias still_nm_struct = NmStruct(1) + NmStruct(2)# When materializing to a run-time variable, it is automatically converted,# even without a type annotation.var converted_to_has_bool = still_nm_struct