Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str.equals("String") vs "String".equals(str) [duplicate]

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.

like image 446
knpwrs Avatar asked Mar 17 '23 19:03

knpwrs


1 Answers

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.

like image 171
Eran Avatar answered Mar 30 '23 03:03

Eran