Dynamic vs Inline RegExp performance in JavaScript

后端 未结 3 1032
鱼传尺愫
鱼传尺愫 2020-12-25 11:03

I stumbled upon that performance test, saying that RegExps in JavaScript are not necessarily slow: http://jsperf.com/regexp-indexof-perf

There\'s one thing i didn\'t

3条回答
  •  臣服心动
    2020-12-25 11:20

    The difference in performance is not related to the syntax that is used is partly related to the syntax that is used: in /pattern/ and RegExp(/pattern/) (where you did not test the latter) the regular expression is only compiled once, but for RegExp('pattern') the expression is compiled on each usage. See Alexander's answer, which should be the accepted answer today.

    Apart from the above, in your tests for inlineRegExp and storedRegExp you're looking at code that is initialized once when the source code text is parsed, while for dynamicRegExp the regular expression is created for each invocation of the method. Note that the actual tests run things like r = dynamicRegExp(element) many times, while the preparation code is only run once.

    The following gives you about the same results, according to another jsPerf:

    var reContains = /(?:^| )foo(?: |$)/;
    

    ...and

    var reContains = RegExp('(?:^| )foo(?: |$)'); 
    

    ...when both are used with

    function storedRegExp(node) {
      return reContains.test(node.className);
    }
    

    Sure, the source code of RegExp('(?:^| )foo(?: |$)') might first be parsed into a String, and then into a RegExp, but I doubt that by itself will be twice as slow. However, the following will create a new RegExp(..) again and again for each method call:

    function dynamicRegExp(node) {
      return RegExp('(?:^| )foo(?: |$)').test(node.className);
    }
    

    If in the original test you'd only call each method once, then the inline version would not be a whopping 2 times faster.

    (I am more surprised that inlineRegExp and storedRegExp have different results. This is explained in Alexander's answer too.)

提交回复
热议问题