-6

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()

Boris Lebedev
  • 143
  • 2
  • 10
  • 4
    Are you doing like a million `.trim()` actions on a button click? If not, who cares? – Pointy Nov 18 '21 at 15:58
  • 1
    Maybe go start with [How do you performance test JavaScript code?](https://stackoverflow.com/q/111368/1427878) ... – CBroe Nov 18 '21 at 16:00
  • 1
    [If only there was a way to test this](https://jsbench.me/1xkw559809/1) – Jamiec Nov 18 '21 at 16:04

1 Answers1

1

Test:

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()

Results:

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)

Conclusion:

trim is faster

Source:

https://www.measurethat.net/Benchmarks/Show/4767/0/regex-removing-whitespace-vs-trim

eglease
  • 2,445
  • 11
  • 18
  • 28