Andrew Gray
Andrew Gray

Reputation: 3790

JavaScript Enumeration object - faster with strings, or numbers?

In a project I am working on, we have a script with an 'enumeration' object in it, as such:

var MyEnumeration = {
    top: "top",
    right: "right",
    bottom: "bottom",
    left: "left"
};

When we have to use something that would use one of those literal values, we just do a comparison to MyEnumeration.left or whatever the case is.

However: At least in C#, string values usually evaluate more slowly than numbers, since strings have to do a character-for-character comparision to ensure that string A matches string B.

This brings me to my Question: Would implementing MyEnumeration with number values perform more quickly?

var MyEnumeration = {
    top: 0,
    right: 1,
    bottom: 2,
    left: 3
};

Upvotes: 1

Views: 569

Answers (2)

rsnickell
rsnickell

Reputation: 1262

It varies based on Javascript Engine as this jsperf surprised me:

http://jsperf.com/string-compare-vs-number-compare/2

Running in both FF and Chrome, the results were all over the place as to whether string or number comparisons were faster.

The answer to your question is it depends. If you were to target a single browser, then you may be able to write code that would take advantage of its specific optimizations for comparisons.

Upvotes: 1

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

When comparing strings, JavaScript compares each characters one by one, from left-to-right. But when comparing two numbers, it's just a single comparison. Obviously you can guess which one is faster - the numerical comparison.

However, this kind of optimization might be premature. Unless you really need that efficiency gain (comparing hundreds of values like this frequently, perhaps?), don't think too much about them.

Upvotes: 1

Related Questions