javascriptnode.jsperformancehigh-load

Which is more faster? trim() or RegEx?


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


Solution

  • 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