1

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
};
4
  • Perform more quickly in what respect? If you compare a variable to one of your enumeration values? If so, I think you answered your own question. This smells a little like premature optimization though so tread carefully. Commented Aug 23, 2013 at 19:01
  • I agree that it could be premature optimization, it's something I was just curious about. As far as 'in what respect', I would think that more quickly or more slowly could only refer to execution time, as JavaScript is an interpreted language only...please correct me if I'm wrong. Commented Aug 23, 2013 at 19:05
  • 1
    @AndrewGray: 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. Commented Aug 23, 2013 at 19:15
  • @SayemAhmed - As I suspected. If you wouldn't mind making that an answer, I'd be more than happy to accept. Commented Aug 23, 2013 at 19:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.