Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use lambda expressions instead of foreach? [closed]

Today I was working on a TextToSpeech app and I've came across a situation where I need to check if the selected voice by the user is installed on the computer.

For this, I could either use a foreach:

bool foundVoice = false;
foreach (var v in installedVoices)
{
    if (v.VoiceInfo.Name.Contains(selectedVoice) && v.VoiceInfo.Culture.ToString() == selectedCulture)
    {
        foundVoice = true;
        break;
    }
}

Or a lamda expression:

var foundVoice = installedVoices.FirstOrDefault(v => v.VoiceInfo.Name.Contains(selectedVoice) && v.VoiceInfo.Culture.ToString() == selectedCulture);

The installedVoices is a ReadOnlyCollection< InstalledVoice > from SpeechSynthesizer.

Definitely, the lambda expression looks more cleaner than the foreach but which one is better practice?

From what I have tested the foreach seems to be slightly faster than the lambda expression.

Also, both foreach and lambda can be extended in the future if there is need for immediate action on the InstalledVoice.

like image 763
Dev Catalin Avatar asked Jul 26 '16 11:07

Dev Catalin


2 Answers

the lambda expression looks more cleaner than the foreach but which one is better practice?

"Looks cleaner" is a perfect indicator of a better practice. It is extremely rare for performance to change in a meaningful way depending on the language facility in use, so readability is the most important measure of how good a particular construct is for your code. Readability is what ultimately decides the maintainability of your code, even when the only reader of your code is you.

Note that this is a case-by-case decision, because lambdas may be better in one situation and loops could be better in another situation.

like image 171
Sergey Kalinichenko Avatar answered Nov 12 '22 18:11

Sergey Kalinichenko


Yes, it's good practice to use LINQ in this case, because it's more readable. However, to me installedVoices.Any instead of installedVoices.FirstOrDefault would be even more readable.

like image 41
Henrik Avatar answered Nov 12 '22 18:11

Henrik