3 ms·
Actually no, compilers can't assume that `foo` is const. var foo = 0; eval("foo = 1"); With that said, virtually nobody uses `const` for performance r
by vortico 7y ago
Actually no, compilers can't assume that `foo` is const.
var foo = 0;
eval("foo = 1");
With that said, virtually nobody uses `const` for performance reasons, but for developer readability and avoiding mistakes.
- chrisseaton 7y ago> Actually no, compilers can't assume that `foo` is const. They can assume it, they just need to be able to reverse that assumption if you do change it through something like eval. This is called 'speculative optimisation' and we use it to optimise languages like JavaScript, Ruby, Python, etc.
- deleted 7y ago[deleted]
- AgentME 7y agoA javascript engine can tell that a variable is used in a const-like way if it statically checks that `eval` is not used in the within the variable's scope. I believe there are a few optimizations in V8 and other engines that are disabled if eval is used in the scope at all. (I don't know if there are any optimizations around a variable being used in a const-like way. As you said, const in JS is mainly for developers.) Given code like `function foo(fn, str) { var foo = 0; fn(str); return foo; }`, you might be wondering what happens if foo is called with `foo(eval, "foo = 1");`. The answer is that a standard eval call isn't actually a normal function call but better understood as a special syntax resembling a function call. There's a big difference between `eval(x);` and `var e = eval; e(x);`. When you take the value of `eval` (by passing it as a parameter or assigning it to a variable, etc), the value you get is actually the "indirect eval" function, which works slightly differently than standard eval: it does not get access to the local scope that it's called in. This means its usage won't break any optimizations that assume the local scope won't be modified.