Why isn't 10^6 evaluated at compile time?

Why isn’t @eval as fast as the eval macro from @Mason?

If you write f(x) = x * @eval 10^6, Julia can’t know that it’s safe to do the eval at parse time, it has to wait until the function is actually running. Notice that my macro doesn’t return :(eval($ex)), it first runs eval(ex) and then returns that result, so

julia> @macroexpand @eval_at_parse_time 10^6
1000000

whereas

julia> @macroexpand @eval 10^6
:((Base.Core).eval(Main, $(Expr(:copyast, :($(QuoteNode(:(10 ^ 6))))))))

that’s why the above macro is only really useful for evaluating stuff involving literals. You can’t use local variables, or even global varaibles / functions that are defined after f.

3 Likes