Search code examples
c#linqpremature-optimization

Which one of this syntaxs have better performance?


Which one of this syntax have better performance and speed in searching between data?

First alternative:

this.Message = pageContentsli
    .Where(m => m.PName == "Message")
    .First()
    .ContentValue;

Second alternative:

  foreach (PageContentsModel pc in pageContentsli)
  {
     if (pc.PName == "Message"){
        this.Message = pc.ContentValue;
        break;
      }
  }

Solution

  • Before continuing with the comparison, you should move the condition inside First like this:

    this.Message = pageContentsli.First(m => m.PName == "Message").ContentValue;
    

    As far as the performance goes, you should see no difference. On readability, however, the modified LINQ version wins hands down.