简体   繁体   中英

SAX parser and String interning

I noticed all Strings in DefaultHandler 's event methods are interned. Would it be better to see if Strings are equals with == instead of equals() ?

@Override
public void startElement(String uri, String localName, String qName,
     Attributes attributes) throws SAXException {

if(localName == "element")
// do something

// or

if(localName.equals("element"))
// do something

}

Since all String literals are interned, it should improve performance. But all the tutorials and examples I've seen use equals()

A problem I can see is if you need to use equalsIgnoreCase()

At least in Oracle JDK7, the very first thing String.equals(Object) does is check if the object reference is the same as the String instance:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    ...

So, even if == in these cases would yield correct results, the only savings you have accomplished are a method call that (almost) immediately returns. I doubt that the cost savings would be noticeable in any sort of measurement.

Even if there was some measurable cost savings, it seems like it would be a very risky optimization - to always assume that == comparisons are correct for these Strings. What if a future version of the SAX class changes behavior? Is string interning a documented feature of it's API? Sounds doubtful.

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