xp-framework / compiler

Compiles future PHP to today's PHP.
19 stars 0 forks source link

For with ranges #134

Closed thekid closed 2 years ago

thekid commented 2 years ago

Like the for..in-loop in JavaScript and Kotlin's ranges:

// Be able to replace this:
for ($i= $this->lo; $i <= $this->hi; $i++) {
  // ...
}

// ...with this:
for ($i in $this->lo..$this->hi) {
  // ...
}
thekid commented 2 years ago

Should for ($i in $this->lo..$this->hi) be rewritten to:

The reason for rewriting to foreach could be to also use for ($i in <iterable>), and think of <A>..<B> as a range expression instead of just loop syntax.

thekid commented 2 years ago

[...] think of <A>..<B> as a range expression instead of just loop syntax.

...which would then bring up the following alternative:

foreach ($this->lo..$this->hi as $i) {
  // ...
}
thekid commented 2 years ago

I would only use the range syntax if I knew it resulted in optimized code. See the following benchmark, especially the memory usage of range(), which is far from acceptable!

$j= 0;

// Runtime: 0.261 seconds, 527945.91 kB memory used
foreach (range(0, 10000000) as $i) {
  $j+= $i;
}

// Runtime: 0.131 seconds, 1756.56 kB memory used
for ($i= 0; $i <= 10000000; $i++) {
  $j+= $i;
}

// Runtime: 0.137 seconds, 1756.56 kB memory used
$i= 0;
do {
  $j+= $i;
} while (++$i <= 10000000);

This means when emitting foreach a range should be detected and the for loop should be emitted instead.