// useful for HtmlCollection, NodeList, String types
function forEach(array, callback, scope){for (var i=0,n=array.length; i<n; i++)callback.call(scope, array[i], i, array);} // passes back stuff we need
function countVowels(input)
{
var vowels = 'aeiou', result = 0;
forEach( input, function(char){ if (vowels.indexOf(char) != -1) result++; } );
return result;
}
countVowels("goes");
function VowelCount(str) {
var pattern = /[aeiou]/i;
var vowelCount = 0;
for (var i = 0; i < str.length; i++) {
if (pattern.test(str[i])){
vowelCount++;
}
}
return vowelCount;
}
VowelCount("goes")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach version | |
regexVersion |
Test name | Executions per second |
---|---|
forEach version | 14167874.0 Ops/sec |
regexVersion | 18621818.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided benchmark compares two approaches to count the number of vowels in a given string: using the forEach
method and using a regular expression (regex
). We'll break down what each approach does, its pros and cons, and discuss other considerations.
1. Using forEach
:
function forEach(array, callback, scope) {
for (var i = 0, n = array.length; i < n; i++) {
callback.call(scope, array[i], i, array);
}
}
function countVowels(input) {
var vowels = 'aeiou', result = 0;
forEach(input, function(char) {
if (vowels.indexOf(char) != -1) result++;
});
return result;
}
The forEach
method is a built-in JavaScript function that applies a given callback function to each element of an array. In this case, the callback function checks if the character is a vowel and increments the result accordingly.
Pros:
Cons:
2. Using regular expression (regex
):
function VowelCount(str) {
var pattern = /[aeiou]/i;
var vowelCount = 0;
for (var i = 0; i < str.length; i++) {
if (pattern.test(str[i])) {
vowelCount++;
}
}
return vowelCount;
}
The regular expression [aeiou]
matches any character that is a vowel (both lowercase and uppercase). The i
flag at the end makes the match case-insensitive. In this implementation, we use the test()
method to check if each character is a vowel.
Pros:
forEach
.Cons:
Library usage:
In this benchmark, the forEach
method is a built-in JavaScript function. No external library is used.
Special JS feature:
None mentioned in this specific benchmark. However, it's worth noting that JavaScript has several features that can affect performance, such as:
let
and const
declarations (vs. traditional var
)These features can impact the performance of certain code snippets, but their effects are often subtle and depend on the specific use case.
Alternatives:
If you're interested in exploring alternative approaches to this benchmark, here are a few options:
Keep in mind that the choice of alternative approach depends on your specific use case and requirements.
I hope this explanation helps!