Why do Julia experts use
@nospecialize(ex) in functions used by macros?
E.g. here: Typed globals: macro to define multiple, without manual type annotations - #2 by simeonschaub
I’d say the only types the argument could be are
LineNumberNode, so there’s not a whole lot to optimize by avoiding type specialization.
ex could also be some ‘atom’/literal type I guess)
The short answer is because:
- the type of
ex isn’t known when
@typed ex is called
- it’s not very important to specialize
And so for this kind of case
@nospecialize can avoid runtime dispatch on
rewrite_assignment and will slightly improve the macro expansion of
@typed (although it may not be very important given that the computation happens at lowering time).
rewrite_assignment is defined in a way that it can take arbitrary AST elements other than
Symbol. I agree with that it may not be very important to optimize the computation that only happens at lowering time, but it’s certainly better to have
If you want to have a more understanding on what
@nospecialize really does, the description of this PR may give some idea.