[ajug-members] creating strings

dB dbostwick at mindspring.com
Sun Jul 22 14:39:07 EDT 2007


Hey Sony,

There is a big difference in both memory and performance between the two.

The first case, String s = new String("XXX"); creates two string objects,
one on the heap (well, it may eventually get there after eden space) and
another "constant" string in the string cache.  More object creation, less
memory, less speed.

The second case just creates one string "constant" and stores it in the
string cache.  Since only one object is created, this approach is faster and
consumes less memory.

Check out Joshua Bloch's book "Effective Java Programming Language Guide."
In particular, item 4 describes this very problem.

Hope this helps,

dB

-----Original Message-----
From: ajug-members-bounces at ajug.org [mailto:ajug-members-bounces at ajug.org]
On Behalf Of Sony Antony
Sent: Saturday, July 21, 2007 10:55 PM
To: General AJUG membership forum (100-200 messages/month)
Subject: [ajug-members] creating strings

Is there any different between teh following string instantiations at run
time ( memory, speed of execution etc. )

String s = new String( "XXX") ;

String s = "XXX" ;


I thought they are both exactly same as new strings are created only if
there isn't already an entry in the string table for the same string.


--sony
_______________________________________________
ajug-members mailing list
ajug-members at ajug.org
http://www.ajug.org/mailman/listinfo/ajug-members





More information about the ajug-members mailing list