0

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()

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing that out. The SAX parsers I use have String interning feature, but it may change like you said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.