Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  113] [ 1]  / answers: 1 / hits: 20881  / 12 Years ago, tue, september 11, 2012, 12:00:00

A few weeks ago, I have read this thread Is < faster than <=? about comparison operators in C. It was said that there is no difference in the performance between < and <= as they are interpreted as same/similar machine commands.



At the same time, in our company's best practices, it was said that we should always use === to compare things instead of ==. So, I started to wonder if this is always appropriate as I am used to using the == and typeof ... == and do not want to change my way of writing :-]



Note that this is in the context of JavaScript.



So, I have a little research and here Which equals operator (== vs ===) should be used in JavaScript comparisons? it is said that:




This is because the equality operator == does type coercion...meaning
that the interpreter implicitly tries to convert the values and then
does the comparing.



On the other hand, the identity operator === does not do type
coercion, and so thus it does not convert the values of the values
when comparing




And I started to wonder if this means that when I use the === operator, I will get good performance as no resources will be spent on converting the operands. And after all code is turned into machine commands, does this mean that just as there is no difference in C when you use < and <=, this is the same in JavaScript and other languages?


More From » performance

 Answers
20

for js, the === operator will return true if used on string types and the strings are exactly the same characters. For objects it compares the object references, not the contents.


From the ECMA standard:



11.9.6 The Strict Equality Comparison Algorithm The comparison x === y, where x and y are values, produces true or false. Such a comparison
is performed as follows:



  1. If Type(x) is different from Type(y), return false.

  2. If Type(x) is Undefined, return true.

  3. If Type(x) is Null, return true.

  4. If Type(x) is Number, then
    a. If x is NaN, return false.
    b. If y is NaN, return false.
    c. If x is the same Number value as y, return true.
    d. If x is +0 and y is -0, return true.
    e. If x is -0 and y is +0, return true.
    f. Return false.

  5. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in
    corresponding positions); otherwise, return false.

  6. If Type(x) is Boolean, return true if x and y are both true or both false;



[#83133] Monday, September 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skyler

Total Points: 646
Total Questions: 119
Total Answers: 96

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;