Open mkustermann opened 3 weeks ago
Labels: area-web
, type-bug
Summary: The toJS
method on string literals is not being constant folded in dart2js, resulting in unnecessary JavaScript code generation. This leads to larger and less efficient code compared to manually inlining the string literal.
Constant-folding of final top-level/static variables is mostly done by CFE.
final foo = 123;
is handled somewhat like const foo = 123;
because dart2js can see the RHS is a constant in the Kernel IR.
Unfortunately, dart2js does not compile using a full callgraph-bottom-up schedule, so the non-const initializer expression that reduces to a constant it not seen by the users of the variable.
We could do something more limited if this is a popular code pattern./
We could do something more limited if this is a popular code pattern./
The reason I used that pattern in a benchmark is because on dart2wasm this is not a NOP and we'd do the key conversion every single time we do a map lookup. So it makes sense to hoist it there to top-level which then regresses dart2js.
If we recognize this specially in dart2wasm compiler (see https://github.com/dart-lang/sdk/issues/56046) then using the pattern inline in code (rather than top-levels) would not be needed.
Though any 3rd party user may also think it's more efficient to cache in a top level instead of executing every time - and it would be worse performance. So I think maybe it's a good idea to do this optimization regardless.
The following example
compiles (with
dart compile js --no-minify -O4 -o repro.js repro.dart
) to:When instead manually inlining this in dart to
then this becomes
/cc @srujzs @rakudrama