R
R
ragnar_ok2021-07-23 19:38:57
PHP
ragnar_ok, 2021-07-23 19:38:57

When is it useful to use a generator if the amount of data is small?

If you need to iterate the same array multiple times, would it be more efficient to use a generator than foreach? What if you pass an array to a function by reference?

Prepared an example. Theoretical.

spoiler
/**
 * @param string[] $array
 */
function setFoo(array &$array): void
{
    foreach ($array as &$item) {
        if ($item === 'foo') {
            $item = 'baz';
        }
    }
}

/**
 * @param string[] $array
 */
function setBar(array &$array): void
{
    foreach ($array as &$item) {
        if ($item === 'bar') {
            $item = null;
        }
    }
}

$array = [
    'foo',
    'bar',
];

setFoo($array);
setBar($array);


sandbox.onlinephpfunctions.com/code/cab17cc19053f0...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2021-07-23
@ragnar_ok

Efficiency has nothing to do with it at all.
The generator is a syntactic sugar
That is, the question is not about efficiency at all
, by golly, some kind of illness or something.
you have any function is evaluated only on one basis - "efficiency"! Which one is faster - this one is better.
That's it, there are no other criteria. and vice versa - if someone whistled somewhere that one function is "more effective" than another - then everything, only this one is used everywhere, contrary to logic and common sense. because it's more efficient!
But in fact there are other criteria.
The generator has one uniquely useful application - the ability to create unified interfaces.
It can turn any stream source into a traversable one.
That is, you can spawn interfaces and feed them to some forich, and he will work with them without knowing whether the stream is inside, or the array. The file, the result of a query from the database, the decoded jason - if each of these sources has an iterable interface, then all of them can be iterated in the same loop.
And for the sake of such unification, a generator is used

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question