var strings = [' ', ' a', 'a ', ' a '];
strings.filter(s=>/^\s+$/.test(s));
strings.filter(s=>!s.trim())
strings.filter(s=>s.trimStart())
strings.filter(s=>s.trimEnd())
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
trim | |
trimStart | |
trimEnd |
Test name | Executions per second |
---|---|
regex | 5549701.0 Ops/sec |
trim | 10098110.0 Ops/sec |
trimStart | 10933349.0 Ops/sec |
trimEnd | 11619358.0 Ops/sec |
The benchmark defined in the provided JSON tests various methods for detecting empty strings, particularly focusing on how these methods handle strings with leading or trailing whitespace. This scenario is highly relevant to developers working with user inputs, where it is essential to handle strings correctly.
Objective: To evaluate performance when filtering an array of strings to determine if they are empty after removing whitespace using various techniques.
Tested Methods:
Regular Expression:strings.filter(s => /^\\s+$/.test(s));
This method uses a regular expression to check if the string consists solely of whitespace.
Trim:strings.filter(s => !s.trim());
This checks if the string, when trimmed of whitespace from both ends, is empty.
Trim Start:strings.filter(s => s.trimStart());
This uses the trimStart()
method to remove whitespace from the beginning of the string only and checks if the result is truthy (non-empty).
Trim End:strings.filter(s => s.trimEnd());
Similarly, this uses the trimEnd()
method to remove whitespace from the end of the string and checks if the result is truthy.
The benchmark results provide the number of executions per second for each method using a specific browser, device platform, and operating system. Here are the results:
Regular Expression
Trim Method
trim()
is specifically designed for this purpose and operates optimally for removing leading and trailing whitespace.trimStart()
or trimEnd()
if only one side is of interest, but still quite efficient in practice.Trim Start and Trim End
trim()
when relevant.trim()
, trimStart()
, and trimEnd()
are widely supported in modern browsers, using regular expressions can bring up concerns regarding readability and maintainability of the code.Aside from these methods, other approaches might include:
Choosing the appropriate method not only depends on performance results but also on the specific needs and context of the application, such as code maintainability and readability.