• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

SCJP5: Heap vs String constant pool

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've been studying for the SCJP5 exam and came across the following:

1) String s1 = new String("abc");

2) StringBuilder s2 = new StringBuilder("abc");

Someone told me that line 2 is more efficient (in memory use) than line 1.
I know that StringBuilder makes better use of memory because it's not immutable, but it seems to me that line 2 by itself can't be more efficient than line 1, because:

line 1: creates one String object in the heap and another String object in the String constant pool because of the "abc".

line 2: creates one StringBuilder object in the heap and a String object in the String constant pool because of the "abc".

Am I right about this?
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Performance wise, it will be too small to measure with the strings you've provided, its insignificant. Obviously, StringBuilder had a definite advantage when it comes to building a big String (eg. building a String in a loop).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic