str.equals("String") vs "String".equals(str)

java, performance, string

Solution

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.

Problem

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.

Original source

Related problems