C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
There are several different ways you can test for vowels. This test can be used in textual transformations, such as those that correct spelling errors. We examine here the is-vowel test.
Vowels: a, e, i, o, u
Tests. Let's look at the first version of the Vowel() method, VowelA(). This method uses a switch-statement to test the formal parameter letter. Switch statements are sometimes faster than if-statements.
Here: The method returns true for lowercase "aeiou", and false in all other cases. The input string is assumed to be lowercase.
Version A: C# static bool VowelA(char letter) { switch (letter) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; default: return false; } } Benchmark result 245.04 ns
Version B. Next we see the second version of VowelB(). This method was much faster on the input string. This might be because English words have a lot of vowels or that the switch statement was inefficient.
And: We use a chained expression. It will exit early when an expression evaluates to true.
Version B: C# static bool VowelB(char letter) { return letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u'; } Benchmark result 192.92 ns
Version C. Finally, we change the order. To create this version, I determined the frequency of vowels in the English language by using Wikipedia. We test for the most common vowels first and the least common last.
Version C: C# static bool VowelC(char letter) { return letter == 'e' || letter == 'a' || letter == 'o' || letter == 'i' || letter == 'u'; } Benchmark result 190.09 ns
Discussion. To benchmark, I measured these methods by calling them on each character of a 13-character string in a loop. I called the method five times per each letter. This means the method was called 65 times on the input string.
Input string used: C# string input = "The Developer Blog"; Inner benchmark loop: C# for (int y = 0; y < input.Length; y++) { char letter = input[y]; VowelA(letter); VowelA(letter); VowelA(letter); VowelA(letter); VowelA(letter); }
Models. Computer programs are best when they model the real world. This Vowel method is a simple example of this: when it tests characters in a way that mirrors the frequency of characters in the real world, it is most effective.
And: This can be considered an isomorphism to the real world, in that the structure of the program is based on the English language.
Summary. We optimized a simple method in the C# language based on real-world data. When programs are structured in such a way that they mirror aspects of the real world, they are often more efficient and of higher general quality.