Is there any difference in equals and == for String variables?
Yes there is a major difference, Case sensitivity.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm
> equals(stringOrId) Returns true if the passed-in object is not null and represents the same binary sequence of characters as the current string. Use this method to compare a string to an object that represents a string or an ID.
== is same as equalsIgnoreCase(secondString)
Returns true if the secondString is not null and represents the same sequence of characters as the String that called the method, ignoring case.
I would add that ==
is more null safe. Consider the following examples.
String a;
String b = null;
system.assert(a == b);
This will pass.
String a;
String b = null;
system.assert(a.equals(b));
This will throw a null pointer exception.
The above demonstration is why I tend to prefer ==
over .equals
. If you are going to use .equals
, you should always first check that it is not null, though it is not necessary when using constants.
final String SOME_CONSTANT = 'abc';
...
if (SOME_CONSTANT.equals('abc'))
{
// do stuff
}
if (someParameter == SOME_CONSTANT)
{
// do other stuff
}
Also note that while .equals
is case sensitive, you can still call .equalsIgnoreCase
.
In addition to what I've already stated, I did some informal profiling and it seems ==
may be significantly faster than .equals
. More than 7 times as fast.
.equals
String a = 'abc';
String b = 'abc';
DateTime start = Datetime.now();
for (Integer i = 0; i < 100000; i++) Boolean isEqual = a.equals(b);
Decimal interval = Datetime.now().getTime() - start.getTime();
system.debug(interval); // yields 1831
.equalsIgnoreCase
String a = 'abc';
String b = 'abc';
DateTime start = Datetime.now();
for (Integer i = 0; i < 100000; i++) Boolean isEqual = a.equalsIgnoreCase(b);
Decimal interval = Datetime.now().getTime() - start.getTime();
system.debug(interval); // yields 1514
==
String a = 'abc';
String b = 'abc';
DateTime start = Datetime.now();
for (Integer i = 0; i < 100000; i++) Boolean isEqual = a == b
Decimal interval = Datetime.now().getTime() - start.getTime();
system.debug(interval); // yields 239
Even the slowest of these is consuming less than 1/5 ms per execution, but if you get in a big loop and your calls start to number in the millions, that can add up.