4

Is there a performance impact, assuming str is a java.lang.String, of using "String".equals(str) vs str.equals("String")? My gut says, "No, the JVM / compiler will optimize the literal string in either case", but I see the first style crop up enough in various codebases and it just looks so unnatural (at least to me), so I figured there must be a reason besides style.

Eran
  • 374,785
  • 51
  • 663
  • 734
knpwrs
  • 14,665
  • 11
  • 59
  • 99

2 Answers2

7

The only reason for using "String".equals(str) (which I find ugly) is laziness, as it saves you the need to check that str != null prior to calling str.equals("String").

Performance-wise there shouldn't be any difference. You are comparing two String instances either way.

Eran
  • 374,785
  • 51
  • 663
  • 734
0
"String".equals(str)

Does not yield the same result as

str.equals("String")

if str == null.

In the first case, it returns false, in the second, it throws a NullPointerException.

"String".equals(str)

Is in fact equivalent to

str != null && str.equals("String")
njzk2
  • 38,125
  • 7
  • 64
  • 103