[jdom-interest] getText() returns null or ""

Alex Chaffee guru at edamame.stinky.com
Fri Oct 6 09:56:19 PDT 2000


OK, let me put this to rest.  "".equals("") is not slow!  The source
code for java.lang.String says

    public boolean equals(Object anObject) {
	if (this == anObject) {
	    return true;
	}
	if ((anObject != null) && (anObject instanceof String)) {
	    String anotherString = (String)anObject;
	    int n = count;
	    if (n == anotherString.count) {
		char v1[] = value;
		char v2[] = anotherString.value;
		int i = offset;
		int j = anotherString.offset;
		while (n-- != 0) {		// <<<<<<<<
		    if (v1[i++] != v2[j++]) {
			return false;
		    }
		}
		return true;
	    }
	}
	return false;
    }

which means that 

(a) if both ""s are constants, it returns immediately (since Java does
constant string pooling, so every empty string is represented by the
same object)

(b) otherwise, since 0==0, it sets some local variables, compares n to
0 ("<<<"), and then returns true immediately

So fuggadabattit!  String compares are actually very fast for strings
that are very short or very different.  The hard part is comparing
strings that are identical for 99 characters and differ on the 100th.

(Yes, it's a bit slower than comparing to null, but in linear time.)

 - A

P.S. Scott, did you send your message 4 times, or is it another
Mailman bug?


On Thu, Oct 05, 2000 at 02:20:13PM +0200, Scott Willy wrote:
> > -----Original Message-----
> > From: jdom-interest-admin at jdom.org
> > [mailto:jdom-interest-admin at jdom.org]On Behalf Of Laurent Bihanic
> > Sent: Wednesday, 04 October, 2000 16:35
> > To: jdom-interest at jdom.org
> > Subject: Re: [jdom-interest] getText() returns null or ""
> > 
> > 
> > 
> > On the performance side, a test against null is much faster than 
> > an equals()
> > on strings.
> > 
> 
> In the general case, yes, but 
> 
> 	if (foo.equals( "" ) )
> 
> is the same as
> 
> 	if ( foo.length() == 0 )
> 
> and the latter is as fast as a test against null (or as near as d*** it :-)
> 
> 
> Moot point.
> 
> csw
> _______________________________________________
> To control your jdom-interest membership:
> http://lists.denveronline.net/mailman/options/jdom-interest/youraddr@yourhost.com



-- 
Alex Chaffee                       mailto:alex at jguru.com
jGuru - Java News and FAQs         http://www.jguru.com/alex/
Creator of Gamelan                 http://www.gamelan.com/
Founder of Purple Technology       http://www.purpletech.com/
Curator of Stinky Art Collective   http://www.stinky.com/



More information about the jdom-interest mailing list