简体   繁体   中英

Java String Comparison: style choice or optimization?

I've been taking a look at some GWT code written by various people and there are different ways of comparing strings. I'm curious if this is just a style choice, or if one is more optimized than another:

"".equals(myString);

myString.equals("");

myString.isEmpty();

Is there a difference?

"".equals(myString);

will not throw a NullPointerException if myString is null. That is why a lot of developers use this form.

myString.isEmpty();

is the best way if myString is never null, because it explains what is going on. The compiler may optimize this or myString.equals("") , so it is more of a style choice. isEmpty() shows your intent better than equals("") , so it is generally preferred.

请注意,Java 6中添加了isEmpty() ,不幸的是,如果您不支持Java 1.4,仍然会有人大声抱怨。

apache StringUtils provides some convenience methods for, well, String manipulation.

http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.CharSequence)

check out that method and associated ones.

myString.isEmpty() is probably best if you are working on a recent version of Java (1.6). It is likely to perform better than myString.equals("") as it only needs to examine one string.

"".equals(myString) has the property of not throwing a null pointer exception if myString is null. However for that reason alone I'd avoid it as it is usually better to fail fast if you hit an unexpected condition. Otherwise some little bug in the future will be very difficult to track down.....

myString.equals("") is the most natural / idiomatic approach for people wanting to keep compatibility with older Java versions, or who just want to be very explicit about what they are comparing to.

Both of the options using "" may require the creation of a temporary String object but the .isEmpty() function shouldn't.

If they bothered to put the .isEmpty() function in I say it is probably best to use it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM