var string = `A CBASCDASC cascasc qwcqwcqwc qwcqwfcqwc
asas
as
as
asas`
let i = 0;
let num = 0;
while (i < string.length) {
if (/\s/.test(string[i])) {
++num;
}
i++;
}
let i = 0;
let num = 0;
while (i < string.length) {
if (" \f\n\r\t\v\u00A0\u2028\u2029".includes(string[i])) {
++num;
}
i++;
}
let i = 0;
let num = 0;
function test(ch) {
switch (ch) {
case " ":
case "\f":
case "\n":
case "\r":
case "\t":
case "\v":
case "\u00A0":
case "\u2028":
case "\u2029":
return true;
}
return false;
}
while (i < string.length) {
const text = string[i];
if (test(text)) {
++num;
}
i++;
}
let i = 0;
let num = 0;
while (i < string.length) {
const ch = string[i];
switch (ch) {
case " ":
case "\f":
case "\n":
case "\r":
case "\t":
case "\v":
case "\u00A0":
case "\u2028":
case "\u2029":
++num;
}
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
manual | |
switch | |
inline |
Test name | Executions per second |
---|---|
regex | 105483.6 Ops/sec |
manual | 123752.8 Ops/sec |
switch | 138736.7 Ops/sec |
inline | 137117.0 Ops/sec |
I'd be happy to help you understand the benchmark being tested on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance of three different approaches for detecting whitespace characters in a string:
Options Compared
Pros and Cons of Each Approach
Switch Statement
Library Used (Manual Checking)
The Manual Checking approach uses an array of strings representing all possible whitespace characters. The library used is not explicitly mentioned, but it's likely a simple array of character literals or a string constant in JavaScript.
Special JS Feature/ Syntax (Switch Statement)
The Switch statement approach uses the switch
keyword and the case
clause to define the behavior for each possible input value.
Other Alternatives
If you need to detect whitespace characters, other alternatives might include:
DOMParser
or XMLSerializer
to parse the string and extract whitespace charactersindexOf
, includes
)Keep in mind that these alternatives may have different trade-offs in terms of performance, simplicity, and flexibility.