Can `parse` be computed at compile time?

The function
f() = parse(Int, "10")
produces native code, according to @code_native, which involves runtime parsing rather than directly returning the integer 10.

Why can’t Julia optimize this away at compile time? Is it possible for future versions of Julia to do this?

This is governed by Julia’s effect system, see @assume_effects.

Basically, a call may be constant folded when the compiler determines it has the :foldable effect. In this case I think the String ("10") may be complicating things, because there’s some special casing for String. This wouldn’t apply to AbstractString in general.

2 Likes

Why are you using parse in the first place if all you need is a constant?

1 Like

I’m just trying to understand the limits of the compiler’s constant-folding capabilities. I read somewhere that small arrays can be constant-folded, so I wonder to what extent the compiler can do it for strings.

See the comment by Keno here:

1 Like