8
The programming language I use the most is PHP :( and, after it has been implemented Generators in version 5.5, it is said to be faster to use it for generating numbers in sequence than with the function range
- which creates a array
with the sequence, unlike the Generator, that could generate a 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 exit would be:
xrange(); // Generator(object)
According to the staff of PHP, in a numerical sequence generation with range
in PHP with 1000000 would use more than 100MB of memory, while with a Iterator
who would do the same thing, spend 1kb in memory.
Python
Based on this, I realized that in Python the sequences generated by range
are lists, different from the version 3, that returns an object Range
.
Also in Python there is a function called xrange
(which is imitated by PHP in this page), that returns a Generator
.
The point is: The fact of range
in Python returning a list would not make this function more expensive, as for memory, because of the list
that is generated?
If I want to make one range
of 1 to 1000, in Python, it would be more advisable to use xrange
, or the very range
would not harm the memory consumption?
-1 by comparing python to php :P. The question is about python and has the php tag all right? -1 was a joke, +1
– rray
@rray is the "language addiction". Did anyone notice the pun? Well, the intention was to put Python even, value ;)
– Wallace Maxters
About php: Looking at some examples, not in all cases was faster, there were cases that were the opposite, but in memory consumption it was the great advantage for php. A
range(0, 1000000)
can result in more than 100mb of memory consumption or.0 ... Already with Generator will be a few kb.– Guilherme Nascimento
I think recent versions of Python already implement range() as xrange() and the performance difference no longer exists.
– epx