Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield keyword value added?

still trying to find where i would use the "yield" keyword in a real situation.

I see this thread on the subject

What is the yield keyword used for in C#?

but in the accepted answer, they have this as an example where someone is iterating around Integers()

public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}

but why not just use

list<int>

here instead. seems more straightforward..

like image 224
leora Avatar asked Dec 21 '08 12:12

leora


People also ask

What is the yield keyword?

yield keyword is used to create a generator function. A type of function that is memory efficient and can be used like an iterator object. In layman terms, the yield keyword will turn any expression that is given with it into a generator object and return it to the caller.

Is yield a valid keyword?

yield is a keyword that is used like return , except the function will return a generator.

How do you find the yield value?

The yield keyword converts the expression given into a generator function that gives back a generator object. To get the values of the object, it has to be iterated to read the values given to the yield.

What is the purpose of yield keyword in Python?

The yield keyword in Python controls the flow of a generator function. This is similar to a return statement used for returning values in Python.


1 Answers

If you build and return a List (say it has 1 million elements), that's a big chunk of memory, and also of work to create it.

Sometimes the caller may only want to know what the first element is. Or they might want to write them to a file as they get them, rather than building the whole list in memory and then writing it to a file.

That's why it makes more sense to use yield return. It doesn't look that different to building the whole list and returning it, but it's very different because the whole list doesn't have to be created in memory before the caller can look at the first item on it.

When the caller says:

foreach (int i in Integers())
{
   // do something with i
}

Each time the loop requires a new i, it runs a bit more of the code in Integers(). The code in that function is "paused" when it hits a yield return statement.

like image 193
Daniel Earwicker Avatar answered Oct 07 '22 15:10

Daniel Earwicker