const strings = [];
for (let i = 0; i < 1000; ++i) {
const string = i % 2 === 0 ? ' ' : (Math.random() * 100000).toFixed(0).toString()
strings.push(string);
}
window.strings = strings;
function isNullOrWhitespace(str) {
return !str || !str.trim();
}
window.strings.forEach(string => isNullOrWhitespace(string));
const regExp = /^ *$/;
function isNullOrWhitespace(str) {
return !str || regExp.test(str);
}
window.strings.forEach(string => isNullOrWhitespace(string));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Trim | |
RegExp |
Test name | Executions per second |
---|---|
Trim | 93113.4 Ops/sec |
RegExp | 45577.9 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is being tested?
The provided benchmark tests two approaches to detect whether a string is null or whitespace: using the trim()
method and regular expressions (RegExp
).
Options compared:
trim()
method, which removes leading and trailing whitespace from a string./^ *$/
to match strings that consist only of whitespace characters.Pros and Cons of each approach:
Trim() method:
Pros:
Cons:
RegExp:
Pros:
Cons:
/^ *$/
needs to be defined)Other considerations:
window.strings
array is populated with 1000 strings before running the test, which may affect the results.isNullOrWhitespace()
function is called on each string in the array, which means that the function itself is included in the benchmark.Libraries and special JS features:
There are no libraries used in this benchmark. However, it's worth noting that some browsers may have specific optimizations or quirks when using regular expressions for string comparison.
Other alternatives:
If you wanted to test other approaches to detect null or whitespace strings, you could consider:
/^\s*$/i
to match strings with only whitespace characters and ignore case)String.prototype === undefined || String.prototype.trim() === ''
Keep in mind that these alternatives may not be relevant for this specific benchmark, which is focused on comparing the performance of two simple approaches.