Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are real life applications of yield?

Tags:

yield

c#

.net

I know what yield does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?

(Ideally some problem that cannot be solved some other way)

like image 382
juan Avatar asked Aug 19 '08 22:08

juan


People also ask

What is the example of actual yield?

Reactants are converted to products, and the process is symbolized by a chemical equation. For example, the decomposition of magnesium carbonate to form magnesium oxide has an experimental percent yield of 79 %.

Why is yield used?

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.

What is an example of percentage yield?

Example 1: During a chemical reaction, 0.5 g of product is made. The maximum calculated yield is 1.6 g. What is the percent yield of this reaction? Therefore, the percentage yield of this reaction is 31.25%.


1 Answers

I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement.

The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list.

For example, let's say you have a database query that returns 1 million rows. You could retrieve all rows using a DataReader and store them in a List, therefore requiring list_size * row_size bytes of memory.

Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time. In effect this gives you the ability to provide a "streaming" capability over large sets of data.

Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required. If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example).

Regarding:

Ideally some problem that cannot be solved some other way

The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed. There are very few problems (if any) that can't solved more than one way.

Here are a couple of more recent questions and answers that provide more detail:

Yield keyword value added?

Is yield useful outside of LINQ?

like image 84
Ash Avatar answered Oct 26 '22 21:10

Ash