This is pretty far off the topic of servlets--sorry to have added to it.
But you can get the source for String.java (and most of the java.* packages)
in the JDK, in a file called src.jar.

Suffice it to say that, since String.equals() checks for pointer equality
and object type, then downcasts, and then compares lengths,

  String foo;

  if ("".equals(foo)) ...

will never be faster than,

  if (foo != null && foo.length() == 0)

since equals() does the exact same thing, plus some (possibly ellided) type
comparison and downcasting.

Plus, it's rarely what you want: most of the time, you want to treat empty
string and null the same, and non-empty strings differently.  So you
actually want,

  if (foo == null || foo.length() == 0)

But, if you were testing for a _specific_ string,

  if ("Test Me".equals(foo))

_is_ a nice short-hand that avoids testing for null first.  It's still
slower in the case of a null string, than,

  if (foo != null && foo.equals("Test Me"))

for the reasons listed above; but it's better for non-null strings, and it's
at least as easy to understand.

                                        -- Bill K. 

> -----Original Message-----
> From: Beth Kelly [mailto:[EMAIL PROTECTED]]
> Sent: Thursday, August 09, 2001 9:50 AM
> To: [EMAIL PROTECTED]
> Subject: Re: Using Tomcat with MSAccess
> 
> 
> 
> Kyle Wayne Kelly
> (504)391-3985
> http://www.cs.uno.edu/~kkelly
> ----- Original Message -----
> From: "William Kaufman" <[EMAIL PROTECTED]>
> To: <[EMAIL PROTECTED]>
> Sent: Thursday, August 09, 2001 7:14 AM
> Subject: RE: Using Tomcat with MSAccess
> 
> 
> > > <snip />
> > > > > "".equals(passwd)
> > > > > rather than
> > > > > passwd.equals( "" )
> > > <snip />
> > > > No you shouldn't. That's totally evil. For a start, you're
> > > > creating another String object by doing ""
> > > <snip/>
> > > <remark>
> > >   As "" is a constant string, it is created just once. So there
> > >   is not much overhead.
> >
> > True, other than the overhead of calling String.intern() 
> when the class is
> > loaded (JLS 3.10.5).
> >
> > >   ("".equals might be even faster, because
> > >   the jit can inline the method call, as the address of the object
> > >   and the equals method is constant in this case.
> >
> > False.  If the compiler can inline equals(), it can inline 
> length(), too.
> > (In fact, it's more likely to inline length(), since it's a 
> far simpler
> > method.)
> I wonder if equals() is implemented with a bitwise "and".  If 
> that were the
> case, then the first invocation of equals would be simpler 
> than the length
> method (that is with delayed lazy evaluation).
> >
> > (And take a look at the source for String.equals(): at best, with
> comparable
> > inlining of the two methods, you've added an "instanceof" 
> and a downcast,
> > which likely swamps any time taken for the rest of the comparison.)
> >
> >                                         -- Bill K.
> 
> 

Reply via email to