Hellow, what do you think about using generated functions for constants like this?
@generated get_const() = :($([i for i = 1:100_000_000])) # constant is evaluated when called
Hellow, what do you think about using generated functions for constants like this?
@generated get_const() = :($([i for i = 1:100_000_000])) # constant is evaluated when called
There is a pretty involved discussion about this topic here: Constant propagation vs generated functions
You don’t need @generated
for this, just @eval
.
I can imagine two behaviors you might want for a function like this:
get_const()
, creating a new memory each timeI think the standard ways to do this would be something like
const myconst = collect(1:100_000_000)
get_const1() = myconst
and
get_const2() = collect(1:100_000_000)
The generated function approach for this use case has a couple of problems. First, It’s not immediately clear which behavior it will have. Testing it shows that it behaves like (1) above, though there are no guarantees! For generated functions, the compiler can choose when to regenerate the code.
Generated functions are also harder for most users to read, so you should use them only when there’s a clear advantage over a more idiomatic approach.