-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Chuck,

On 5/12/2009 5:03 PM, Caldarale, Charles R wrote:
>> From: David kerber [mailto:dcker...@verizon.net] Subject: Re:
>> Performance with many small requests
>> 
>> When (what java version) did those string operation optimizations 
>> happen?  Sun's web page that talks about this (and explicitly says 
>> that string buffers are usually faster than direct string
>> operations) doesn't mention a specific java version.
> 
> Don't confuse a StringBuffer (the recommended type) with a byte array
> (what Chris was talking about).

Right. People used to write code like this:

String s = ...;
char[] c = s.toCharArray();

for(int i=0; i<c.length; ++i)
   if(c[i] == '\n')
      ...;

Instead of just:

String s = ...;
for(int i=0; i<s.length(); ++i)
  if(s.charAt(i) == '\n')
    ...;

Final method calls got a whole lot quicker at some point (like 1.2 or
1.3) and so the conversion to a char array (or even a byte array) merely
wastes time (for the constructor, memory allocation, etc.) /plus/ the
memory required to duplicate the String's character array. This
"optimization" quickly became a de-optimization.

My position has always been that you should write the code how it ought
to look. Only if it's really causing you performance pain should you
bother to do pinhole optimizations. The JVM authors are more likely to
have an effect on the performance of your code (through optimizations of
things like method calls and monitor lock acquisition) than pinhole
optimizations like the one shown above.

> Since a String object is immutable, one should always use a
> StringBuffer (preferably a StringBuilder, these days) when you are
> constructing strings in a piecemeal fashion, then convert to String
> when complete.

This advice is good when constructing a long string in a loop or across
a long series of statements. If you are just concatenating a bunch of
string together to make a big one in a single statement, go ahead and
use the + operator: the compiler is smart enough to convert the entire
thing into a StringBuilder (a non-synchronized replacement for
StringBuffer) expression that gets good performance without making your
code look like crap.

- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkoKxUcACgkQ9CaO5/Lv0PCo+gCgrlE7HabUgDG+zcba+GFPwZlP
TTEAn2l+hTciWmHGvHH5GSiybnxZfTbi
=nuGH
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org
For additional commands, e-mail: users-h...@tomcat.apache.org

Reply via email to