var str = ' fsajdf asdfjosa fjoiawejf oawjfoei jaosdjfsdjfo sfjos 2324234 sdf safjao j o sdlfks dflks l '
!/\S/.test(str)
!!str.trim().length
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
trim |
Test name | Executions per second |
---|---|
regex | 52948516.0 Ops/sec |
trim | 2186789888.0 Ops/sec |
Let's break down what's being tested on MeasureThat.net.
What is being tested?
The benchmark compares two approaches to check if a string contains whitespace:
!/\S/.test(str)
) to check if the string has any non-whitespace characters.!!str.trim().length
) after removing all whitespace characters.Options compared
The two options are compared in terms of performance, specifically:
Pros and Cons of each approach:
Library used
None, but it's worth noting that the trim()
method is part of the JavaScript String prototype.
Special JS feature or syntax
The question mark !!
before str.trim().length
is an example of optional chaining and the nullish coalescing operator (??
). This syntax allows for more concise expressions and can improve performance by avoiding unnecessary operations. However, it's not a fundamental feature that would be considered essential to understand for general JavaScript programming.
Other alternatives
If you were to write this benchmark yourself, you might also consider comparing other approaches, such as: