Prepack: Non-optimal optimisation in for loop

Created on 4 May 2017  路  2Comments  路  Source: facebook/prepack

The following code is optimised optimally:

Before:

(function() {
  var result = 0;
  for (var i = 0; i < 10; i++) {
    result += i;
  }
  global.result = result;
})();

After:

result = 45;

Changing the initial value of result to an abstract value results in a non-optimal optimisation:

Before:

(function() {
  var result = Math.random();
  for (var i = 0; i < 10; i++) {
    result += i;
  }
  global.result = result;
})();

After:

(function () {
  var _$0 = Math.random();

  if (typeof _$0 !== "number") {
    throw new Error("Prepack model invariant violation: " + _$0);
  }

  result = _$0 + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9;
})();

Expected result:

result = Math.random() + 45;

Most helpful comment

We don't have constant folding of the ast at the end yet. I'd recommend running this through a minifier afterwards that does basic constant folding. Prepack is complimentary to such tools.

All 2 comments

We don't have constant folding of the ast at the end yet. I'd recommend running this through a minifier afterwards that does basic constant folding. Prepack is complimentary to such tools.

Ok thanks, good to know. Closing the issue then.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vojtechkral picture vojtechkral  路  5Comments

matheusml picture matheusml  路  8Comments

kabirbaidhya picture kabirbaidhya  路  6Comments

NTillmann picture NTillmann  路  3Comments

MichaelBlume picture MichaelBlume  路  6Comments