Hacker News new | ask | show | jobs
by tromp 742 days ago
Do you check whether constant folding actually results in shorter code? E.g. something like

    let a="hello "; b=a++a; c=b++b; in c++c
probably shouldn't be changed into

    "hello hello hello hello hello hello hello hello "
4 comments

The Lisp variant that the compiler supports at the moment only handles f64 numbers so I don't think this kind of issue is possible.

However, this is a very relevant point. If the goal is just shorter code (as opposed to a mix of shorter code and less run-time operations), then you need to check that folding strings (and similar types) actually makes the expression shorter to represent.

Depends whether you're optimizing for program size or runtime speed.
If these operations produce mutable strings, the conditions under which that would be allowed are fairly stringent. It's not worth doing; it's better for the Lisp to have constructs that allow the programmer easily stage the evaluation in the desired way.

Common Lisp has load-time-value. It's also easy to write a macro called macro-eval which evaluates its argument at macro time, and substitutes the result (as a quoted object).

What is the case you imagine where mutable strings would prohibit this?
Any situation where the program depends on the expression producing a new string each time it is evaluated, rather than returning the same string. The program may be modifying the string, on the assumption that nothing else has access to it, since it is brand new. The program could also be relying on the string having a unique identity, not comparing equal to any previously seen object. (E.g. assuming that each time the expression is evaluated, it produces an object that can serve as a unique key in an EQ hash table).

Any situation in which these behaviors cannot be ruled out (because the object escapes beyond the scope of analysis), the optimization cannot be applied.

Ah, well all JS strings are always immutable and only value-referable (you have no access to the underlying memory location), so that’s not a concern here.
What about the identity side of it? Does the JS specification say that an operation like "a" + "b" is not required to create a new object? Regardless of whether there is such a spec, you can write code that is sensitive to the difference.
In fact, you cannot. But I encourage you to try!
A sufficiently smart minifier should rewrite that back into `"hello ".times(8)` =)