Web Analytics Made Easy -
StatCounter is regex.test slower than indexOf? - CodingForum

Announcement

Collapse
No announcement yet.

is regex.test slower than indexOf?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • is regex.test slower than indexOf?

    I tend to do stuff like this:
    Code:
    if(/string/.test(variable)) { ....
    Even on single substring matches where indexOf would work - Just because it's more convenient - quicker to type, and extensible.

    But if I'm using quite a few of these, is there any performance impact - is testing a regex literal slower than indexOf?
    "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

  • #2
    According to my testing, it varies wildly between browsers.
    - In op7.5 the indexOf function and comparison operation is slightly faster, by about 80 ms over 1e5 iterations, which hmakes a 12% difference.
    - In moz, the difference is far larger. indexOf and comparison takes more than double the time of the regex. (moz has the best regex engine by far of these browsers, so that's no surprise)
    - In ie6w the difference is four times - in benefit of indexOf plus comparison. The regex speed difference for the browsers is about 100ms between op7.5 (slowest) and moz (fastest), and varies a little between test runs.

    The tests?
    /test/.test('textestext') and 'textestext'.indexOf('test')>-1;, executed over 1e5 iterations in an inverted while loop.
    liorean <[[email protected]]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

    Comment


    • #3
      So IE prefers indexOf, moz prefers the regex, and Opera's not that bothered either way.

      Interesting .. that might be a reason to change some of them - IE is already slower than moz, so maybe it could use the help.

      Ta
      "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

      Comment


      • #4
        Excellent - by using indexOf where it can be, in two of the scripts in my menu, I've got a 13% reduction in the time it take IE to initialise. And moz doesn't seem bothered - it's still faster.

        Nice one. I'll remember that
        Last edited by brothercake; Mar 10, 2004, 12:08 PM.
        "Why bother with accessibility? ... Because deep down you know that the web is attractive to people who aren't exactly like you." - Joe Clark

        Comment

        Working...
        X