Optmizing String Comparisons

This article will discuss a simple optimization to save you a few characters and a little performance when evaluating equality. In JavaScript, there are two types of equality: structural equality (==) where the content of two references are the same, and physical equality (===) where two object point to the same reference or are structurally equal and have the same object type. For the most part I use physical equality when comparing values, to ensure any variable is exactly what it is expected to be. For example, consider this function:

Example 1: Using Physical Equality

function foo(x) {
	if (2 === x) {
		return Matched 2;
	}
	else if (2 === x) {
		return Matched "2"
	}
	else {
		return Did not match;
	}
}

In this simple example, physical equality is used to determine if the provided value is 2 the number or 2 the string.

For all non-string values, I recommend using physical eqaulity and careful type management throughout your code. However, when comparing string variables against string constants (that are not strings of numbers), I recommend using structural equality instead. For example, the following function compares a value against several known constants:

Example 2: Using Structural Equality

function foo(x) {
	if (VALUE1 == x) {
		return Matched 1;
	}
	else if (VALUE2 == x) {
		return Matched "2"
	}
	else {
		return Did not match;
	}
}

In this case there is no need to do the extra type check, because the x is either a string and compared to the value, or it is not a string and will be cast by JavaScript to a string, which will not be equal to the value. So you can save yourself a character by not using === and instead using == in these cases. Additionally, your code may be slightly more performant this way, but I was not able to determine a conclusive performance improvement in my testing.

One exception to this rule, is if you have objects that have overridden the toString methods with functions that return simple strings equal to your comparing constants. JavaScript will use the toString method to convert objects to strings for use with the structural equality comparitor, much like it converts numbers. For example, the following is true:

Example 3: Object Caveat

var Obj = function(){};
Obj.prototype.toString = function() {
	return MYVALUE;
};
var o = new Obj();
return MYVALUE == o;