Are inline JavaScript regular expressions faster?

后端 未结 3 1554
醉梦人生
醉梦人生 2021-01-05 07:09

Is it better to use the RegExp object or the inline style? And why?

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-05 07:29

    According to the ES3 specification, they are slightly different in that the literal syntax (/regex/) will create a single RegExp object upon the initial scan:

    A regular expression literal is an input element that is converted to a RegExp object (section 15.10) when it is scanned. The object is created before evaluation of the containing program or function begins. Evaluation of the literal produces a reference to that object; it does not create a new object.

    The error in that spec was acknowledged in ES4:

    In ES3 a regular expression literal like /ab/mg denotes a single unique RegExp object that is created the first time the literal is encountered during evaluation. In ES4 a new RegExp object is created every time the literal is encountered during evaluation.

    Implementations vary across browsers. Safari and IE treat literals as per ES4, but Firefox and Chrome appear to treat them as per ES3.

    Try the following code in various browsers and you'll see what I mean:

    function f() {
        return /abc/g.test('abc');
    }
    
    alert(f()); // Alerts true
    alert(f()); // Alerts false in FF/Chrome
    

    Compared with:

    function f() {
        return RegExp('abc', 'g').test('abc');
    }
    
    alert(f()); // Alerts true
    alert(f()); // Alerts true
    

    Note, false is alerted because the function is still using the regex from the previous call of that function, the lastIndex of which was updated, meaning that it won't match the string "abc" anymore.


    Tip: the new operator is not required for RegExp to be instantiated. RegExp() by itself works the same...


    More info on the ES3/4 issue: Regex/lastIndex - Unexpected behaviour

提交回复
热议问题