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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With