Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better when using an IEnumerable with one item: yield return or return []?

This is one of those "you can do it many ways" questions. Consider the following code:

protected virtual IEnumerable<ScriptReference> GetScriptReferences()
{
    ScriptReference referece = new ScriptReference();
    referece.Assembly = "FeyenoordEnabled";
    referece.Name = "FeyenoordEnabled.PassTextBox.js";

    return new ScriptReference[] { referece }; 
}

protected virtual IEnumerable<ScriptReference> GetScriptReferences()
{
    ScriptReference referece = new ScriptReference();
    referece.Assembly = "FeyenoordEnabled";
    referece.Name = "FeyenoordEnabled.PassTextBox.js";

    yield return referece;
}

I only need to return one item. The first piece of codes returns an array with a single item and the second one yields the item. What is better and why?

like image 267
Kees C. Bakker Avatar asked Nov 21 '11 21:11

Kees C. Bakker


1 Answers

yield is a pretty expensive keyword. You are telling the compiler to do a lot. If performance isn't an issue, go with the more elegant code. But if performance is an issue, stick with the array.

I can say from past experience that getting rid of this type of yield usage has netted me some serious performance gains. But as always, profile and find the real bottlenecks.

like image 102
Matt Greer Avatar answered Oct 06 '22 07:10

Matt Greer