Is JavaScript string comparison just as fast as number comparison?

后端 未结 3 918
抹茶落季
抹茶落季 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 05:49

    In general, at best String interning (making a string with a given value into a unique reference or a O(1) comparable symbol) is going to take O(n) time, as it can't do that effectively without looking at all the characters involved.

    The question of relative efficiency then amounts to over how many comparisons the interning is going to be amortized.

    In the limit, a very clever optimizer can pull out static expressions which build up strings and intern them once.

    Some of the tests above, use strings which will have been interned in which case the comparison is potentially O(1). In the case where enums are based on mapping to integers, it will be O(1) in any implementation.

    The expensive comparison cases arise when at least one of the operands is a truly dynamic string. In this case it is impossible to compare equality against it in less than O(n).

    As applied to the original question, if the desire is to create something akin to an enum in a different language, the only lookout is to ensure that the interning can is done in only a few places. As pointed out above, different Browser use different implementations, so that can be tricky, and as pointed out in IE10 maybe impossible.

    Caveat lacking string interning (in which case you need the integer version of the enum implementation give), @JuanMendes' string-based enum implementations will be essentially O(1) if he arranges for the value of the myPlanet variable to be set in O(1) time. If that is set using Planets.value where value is an established planet it will be O(1).

提交回复
热议问题