What do you think about using generated functions for constants?

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

1 Like

You don’t need @generated for this, just @eval.

1 Like

I can imagine two behaviors you might want for a function like this:

  1. Allocate once, and reuse always point to the same memory
  2. Allocate at each call to get_const(), creating a new memory each time

I think the standard ways to do this would be something like

const myconst = collect(1:100_000_000)

get_const1() = myconst


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.