Is JavaScript string comparison just as fast as number comparison?

后端 未结 3 914
抹茶落季
抹茶落季 2020-12-15 05:37

I\'d like to write a little library for JavaScript enums. For me to do that, I need to decide how to store the enum values. Therefore, I\'d like to use the fastest way when

3条回答
  •  眼角桃花
    2020-12-15 06:03

    There are cases when string comparison can be much slower (comparing dynamically generated strings)

    The following is 77% slower (in chrome and IE) than all the other tests

    var StringEarth = 'Ear' + 'th';
    for (var i = 0; i < ITERATIONS; i++) {
      x = StringPlanets.Venus === StringEarth;
    }
    

    The flaw in the tests mentioned in the question is the fact that we are testing against literal strings. It seems that JavaScript is optimized so that string comparison for string literals is done just by testing a pointer. This can be observed by creating the strings dynamically. My best guess is that strings from the literal string pool are marked so that they can be compared using addresses only.

    Note that string comparison seems just as fast in FF even for dynamic strings. Also, that it's just as slow for even literal strings.

    Conclusion All browsers behave differently so string comparison may or may not be slower.

提交回复
热议问题