Let's imagine that we have a string we want to check on validity.
Valid string is a string which have at least one non-whitespace symbol and which in not fully whitespaced. (i mean something like 5 whitespaces in a row and nothing else).
I have a two choices to check string validity: use a string.trim() method or use a custom regular expression for that.
I write a very performance dependent application, where every ms is can be a high cost.
So, the question itself: which is faster? regex or string.trim()
var string = ' fsajdf asdfjosa fjoiawejf oawjfoei jaosdjfsdjfo sfjos 2324234 sdf safjao j o sdlfks dflks l '
string.replace(/^\s+|\s+$|\s+(?=\s)/g, '')
string.trim()
Function | Result |
---|---|
regex | regex x 1,458,388 ops/sec ±2.11% (62 runs sampled) |
trim | trim x 7,530,342 ops/sec ±1.22% (62 runs sampled) |
trim
is faster
https://www.measurethat.net/Benchmarks/Show/4767/0/regex-removing-whitespace-vs-trim