Use the C # yield keyword to improve performance and readability

Source: Internet
Author: User

I have seen the keyword "yield" for n times, until recently I have known the power of this keyword. I'll show you some examples of using "yield" to make your code more readable and better performance.

To give you a quick overview of yield, I'll start by showing an example that doesn't use this keyword, the following code is simple, but it's common in my recent projects

Ilist<string> findbobs (ienumerable<string> names) {var bobs = new list<string> (); foreach (var Currname in Names) {if (Currname = = "Bob") bobs. ADD (currname);} return bobs;}

Note here that I use ienumerable<string> as the parameter type and with Ilist<string> as the return type, and generally I prefer to have a wider range of parameters in the type aspect of the input, the better, But more stringent on the return type (the translator presses: the use of a base class or interface for input, a subclass or implementation class when returned), and for input, if you need to loop it with foreach, using IEnumerable is more meaningful. And for the output (the translator presses: that is, to return), I use the interface to make the implementation part can be changed. Here I want to let the caller save the trouble of generating the list, so I choose List as the return type.

The problem is that my design does not have a link, so the design needs to generate the list as the return value, the list may not be very large, but it is not necessary

Now, let's take a look at the "yield" way to do this, and then I'll explain how to use it and how it works.

Ienumerable<string> findbobs (ienumerable<string> names) {foreach (var currname in Names) {if (Currname = = ") Bob ") yield return currname;}}

In this version, we change the return type to IEnumerable, and we use "yield return". Notice I don't need to create a list anymore, is it a bit confusing now? Don't worry, it will become more and more simple to understand the way it works.

When you use the yield return keyword group,. NET generates a bunch of pipe code for you, and you can pretend it's a magic. When you start looping through the called code (this is not a list), what happens on the implementation is that the function is called over and over again, but each time it proceeds from the last part that executed the exit.

traditional methods of execution
    1. Calling functions
    2. function executes and returns a list
    3. The call section uses the returned list
how yield is executed
    1. Calling functions
    2. Caller requested item
    3. The next item returns
    4. Back to step 2

Although the implementation of yield execution may seem complicated, we end up with a "popup" item instead of creating the entire list and returning it.

For the syntax, I personally think that yield is more concise, and for the purpose of the transfer function is better (translator by: That is, code readability), I use IEnumerable as the return type to inform the caller that it can be a foreach loop and return data, The caller can now decide for itself whether it is willing to store the return value in the list, even if it is at the expense of performance.

In this simple example that I have provided, you may not be able to find many benefits of using yield, however, you can save a lot of unnecessary work when the caller needs to cancel the content provided by all functions, and when you use yield on the method link, the amount of work (time) You can save may multiply.

Ayende has a great example: the using yield for a slick pipes & filters implementation, he even tells: version is multi-threaded. It makes me feel very interesting.

At first my reservation to yield was that using this keyword might lead to potential performance problems, but in fact, so far I have not found any information to illustrate the impact of yield on performance, which I mentioned above is far greater than the compiler overhead part.


Yield can make your code more efficient and more readable, already in the. NET 2.0 era, I think there is no excuse to stop us from learning and using yield.


Translator: This article is my translation of the 10 little-known C # keywords in the pangxiaoliang[Beijing] Stray students in the comments put forward the comments, the article just made a summary, I found that there is a deeper in the discussion of the good text, so I do not repeat the invention of the wheel directly translated, In the process of translation I also learned a lot. Thank you.

Original link:

Use the C # yield keyword to improve performance and readability

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.