The programming language I use most is : (), and after it has been implemented Generators in version 5.5, it is said to be faster to use for generating numbers in sequence than with the function range
- which creates a array
with the sequence, unlike the Generator , which could generate one number at a time by yield
.
Example range
PHP:
range(1, 1000); // Retorna: [1, 2, 3, ..., 1000]
Example Generator PHP:
function xrange($start, $limit, $step = 1) {
if ($start < $limit) {
if ($step <= 0) {
throw new LogicException('Step must be +ve');
}
for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be -ve');
}
for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}
The output would be:
xrange(); // Generator(object)
According to PHP staff, in a numerical sequence with range
in PHP with 1000000 would use more than 100MB of memory, whereas with a Iterator
that would do the same thing, would spend 1kb in memory.
Python
Based on this, I noticed that in Python the sequences generated by range
are lists, other than the 3 version, which returns a Range
object.
Also in Python there is a function called xrange
(which is imitated by PHP in this page ), which returns a Generator
.
The question is : Does range
in Python return a list would not make this function more costly than memory, because of the list
that is generated?
If I want to make a range
from 1 to 1000 , in Python it would be more advisable to use xrange
, or range
itself would not hurt to memory consumption?