Closed thekid closed 2 years ago
Should for ($i in $this->lo..$this->hi)
be rewritten to:
for
loop?$i= $this->lo; while ($i++ <= $this->hi) { ... }
(function() { $i= $this->lo; while ($i++ <= $this->hi) yield $i; })()
and foreachrange($this->lo, $this->hi)
and foreachnew Range($this->lo, $this->hi)
and foreach, which would require a Range classThe 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.
[...] 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) {
// ...
}
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.
Like the for..in-loop in JavaScript and Kotlin's ranges: