Yield Return Explained ! (2024)

Yield keyword has always been a highly misunderstood keyword in C#, so I will try to explain it with a simple example so hopefully you can understand it as it will help you to get a better performance for your app.

➽Create the Console App

☞Let's first assume that we have a simple .Net Core 3.1 Console application that handles a list of students.

Student Class will have the following structure:

 public class Student { public int Id { get; set; } public string Name { get; set; } }

Seems simple right ? don't worry, it will keep that way 😉

☞Next step, create a list of Students in the main method of the console app:

 static void Main(string[] args) { CreateStudents(); }

☞So we have a simple function called CreateStudents which takes 1 parameter (Number of students to be created), this function will create students and if the student ID is less than 1000, then it will type it to the screen :

public static void CreateStudents(){ var students = GetStudents(1000000); foreach (var student in students) { if (student.Id < 1000) Console.WriteLine($"Id: {student.Id}, Name: {student.Name}"); else break; }}static IEnumerable<Student> GetStudents(int count){ var students = new List<Student>(); for (int i = 0; i < count; i++) { students.Add(new Student() { Id = i, Name = $"Student Number {i}" }); } return students;}

GetStudents function just creates a new student list and then fill it with new students and return it.

☞let's run the application and see how it behaves and remember again that we want to type only students with ID less than 1000 ...

☞By setting a breakpoint 🔴 after calling GetStudents function, notice that a Million students are created then the foreach loop is entered to print the first 1000 only, so Do we really need to create a million student to print only 1000 😖 ?
Of course not ..

➥What we want is to prevent creating all million records and adding them to a list and returning that list fully hydrated with a million records, instead would it be great if we could just only return what we want.

➽Apply Yield Return

So let's apply some modifications to CreateStudents function ...

static IEnumerable<Student> GetStudents(int count){ for (int i = 0; i < count; i++) { yield return new Student() { Id = i, Name = $"Student Number {i}" }; }}

☞let's run the application now with the same breakpoint set and see what will happen ..

☞We now hit the foreach loop with Zero students created !!

☞let's set another breakpoint in the yield return line inside GetStudents function to see what is really going on and hit Step Over (F10) in Visual Studio to continue the debugging process ...

☞The debugger will go over (students) in the foreach loop then over the (in) keyword then it jumps to the return yield line in GetStudents function without stepping into the foreach in CreateStudents function ...

☞After that we are inside the foreach loop then we enter the if statement and data of the first Student is printed in console ...

☞Continue stepping over using F10 ... you will hit the keyword **in** in the foreach then enter the return yield again ...

➽So what are we really doing here ?

☞Actually we are lazily iterating over the collection of students, we are only requesting one student at a time.

☞In both ways we are getting the same result, which is printing 1000 student on the screen like that

☞The difference between them is that yield return made a huge improve of performance and memory usage that we will see later..

☞Actually, We are basically creating an iterator which iterates through our collection.
Our foreach loop is just a syntactical sugar for a statement like this

var studentesEnumerator = students.GetEnumerator();while (studentesEnumerator.MoveNext()){ var student = studentesEnumerator.Current;}

this is kind of what it compiles down to roughly.

➥So, by not having to iterate over the entire collection, we didn't have to actually create a million student in the list, we actually looped through and only created the first 1000
because using yield when we came into this this loop makes students creation one at a time.

➽Test the difference using BenchmarkDotNet :

● Now, let's test and diagnose the application performance to see if that is really making a difference..

● In this test we will use BenchmarkDotNet Nuget Package to do that, you can download it from here BenchmarkDotNet Nuget

● We will just make simple edits to our code to be able to apply benchmark statistics ...
● We will create a class and let's call it YieldBenchmarks, this class will contain the old version of our functions and the new version using yield return , the class will be decorated with [MemoryDiagnoser] Attribute and the old and new version of CreateStudent functions will be decorated with [Benchmark] Attribute, the code will be as follows

 [MemoryDiagnoser] public class YieldBenchmarks { [Benchmark] public void CreateStudents() { var students = GetStudents(1000000); foreach (var student in students) { if (student.Id < 1000) Console.WriteLine($"Id: {student.Id}, Name: {student.Name}"); else break; } } static IEnumerable<Student> GetStudents(int count) { var students = new List<Student>(); for (int i = 0; i < count; i++) { students.Add(new Student() { Id = i, Name = $"Student Number {i}" }); } return students; } [Benchmark] public void CreateStudentsYield() { var students = GetStudentsYield(1000000); foreach (var student in students) { if (student.Id < 1000) Console.WriteLine($"Id: {student.Id}, Name: {student.Name}"); else break; } } static IEnumerable<Student> GetStudentsYield(int count) { for (int i = 0; i < count; i++) { yield return new Student() { Id = i, Name = $"Student Number {i}" }; } } }

And the main function will be like :

 static void Main(string[] args) { var result = BenchmarkRunner.Run<YieldBenchmarks>(); }

● Now let's run the application in Release mode ...
● Notice that the BenchmarkRunner will run each function multiple time to be able to perform its diagnostics and the result will be like :

● Now Notice the large difference in time elapsed, also notice the huge difference in memory usage, it's 133.5 MB vs 220 KB !!

This was just a simple clarification for the yield keyword, next , we will go with Async Yield .. Wait for it :)

Yield Return Explained ! (2024)

FAQs

What does yield return mean? ›

Yield is the amount an investment earns during a time period, usually reflected as a percentage. Return is how much an investment earns or loses over time, reflected as the difference in the holding's dollar value. The yield is forward-looking and the return is backward-looking.

What are the benefits of yield return? ›

Using yield return, you can read and process each record one by one, reducing the memory footprint significantly. This approach is not just memory efficient but also allows the consumer of this method to start processing data without waiting for the entire file to be read.

What is the difference between yield break and return? ›

The yield keyword is used in two forms: yield return - returns an expression at each iteration. yield break - terminates the iteration.

Why use yield instead of return? ›

When you use a yield keyword inside a generator function, it returns a generator object instead of values. In fact, it stores all the returned values inside this generator object in a local state. If you have used the return statement, which returned an array of values, this would have consumed a lot of memory.

What is a good yield return? ›

Generally speaking, a rental return on property that is 5% or more is considered good. That said, average returns vary greatly depending on the property's: Location: As yields are influenced by both the rental and sales markets, they vary significantly between cities – and across neighbouring suburbs.

Is a 20% yield good? ›

According to the 1996 edition of Vogel's Textbook, yields close to 100% are called quantitative, yields above 90% are called excellent, yields above 80% are very good, yields above 70% are good, yields above 50% are fair, and yields below 40% are called poor.

Which is better yield or return? ›

The importance is relative and specific to each investor. If you only care about identifying which stocks have performed better over a period of time, the total return is more important than the dividend yield. If you are relying on your investments to provide consistent income, the dividend yield is more important.

Is yield the same as roi? ›

Simply speaking, yield is about coupons/dividends vs the price you pay, whereas ROI is your (total) return, i.e. cashflows and price appreciation. They may be related but are really separate concepts.

Is yield the same as profit? ›

The yield of an asset is the amount of cash that an investor will receive in return for buying and holding an investment. This is usually expressed as an annual percentage rate of return. In stocks, the yield is the percentage of a company's profits that is returned to shareholders in the form of dividends.

How to exit yield return? ›

You can use the yield break statement to stop iteration and exit the iterator block. Typically you would do this when a certain condition is met, or you only want to return a specific set of values from the iterator block.

Is yield same as total return? ›

While yield represents the income generated on the investment, total return refers to what an investor has gained or lost on a particular investment.

What does yield mean in investing? ›

What is yield? Yield refers to how much income an investment generates, separate from the principal. It's commonly used to refer to interest payments an investor receives on a bond or dividend payments on a stock. Yield is often expressed as a percentage, based on either the investment's market value or purchase price.

What is the use of yield return? ›

At its core, yield return is a statement used in the iterator method to provide a more efficient way of generating a sequence of values. It allows you to create an iterator without the need to generate an entire collection in memory, making it particularly useful for large datasets or infinite sequences.

Why is yield so important? ›

The yield curve is an important economic indicator because it is: central to the transmission of monetary policy. a source of information about investors' expectations for future interest rates, economic growth and inflation.

What is the purpose of yield? ›

yield : Allows a function to return a value and pause its execution, saving its state. When called again, the function resumes execution right after the yield statement. This makes the function a generator.

Is yield the same as interest rate? ›

Yield represents the total earnings from an investment, including interest. Interest rate is the percentage of the amount borrowed or paid, over a principal amount. Yield typically includes the amount of interest earned.

What is a good yield amount? ›

All in all, though, a good yield is anywhere between 5 and 8%, but you should aim for 7 to 8% or beyond for the best yield on property investment. So when you're wondering what is a good rental yield for your property, aim for somewhere between these numbers.

Top Articles
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 6274

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.