2

I'm newbe in Java and I've got some questions about using constructors:

Map<String, Object> map = new HashMap<String, Object>();
        map.put("one", new String("Hello"));//1
        map.put("two", "world");//2

Which statement is more awfull? What difference? Which one is the best?

anubhava
  • 761,203
  • 64
  • 569
  • 643
Tony
  • 3,605
  • 14
  • 52
  • 84
  • 6
    For `String` use `2`. – Sotirios Delimanolis Sep 26 '13 at 19:42
  • possible duplicate of [What is the purpose of the expression "new String(...)" in Java?](http://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java). Also see http://stackoverflow.com/q/7277650/1281433, http://stackoverflow.com/q/13803505/1281433, – Joshua Taylor Sep 26 '13 at 19:59

3 Answers3

8

Both forms do the same, but there's a difference under the hood. If you use the String constructor, you're skipping the internal string pool, always creating a new object - whereas using the string literal first looks for the string in the pool and if it finds it there, it's reused (only creating a new string if it wasn't in the pool before) - therefore it's more efficient, as it avoid unnecessary object instantiation. By the way, strings can be shared from a pool because they're immutable.

Many static code analysis tools flag the String constructor usage as a violation of good programming practices, and in general it should be avoided.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

First one:

map.put("one", new String("Hello"));//1

is almost never needed. This creates an unnecessary String object. Although it wouldn't matter much at runtime, as it's just a single object. But definitely make a difference when used like this inside some loop. Object creation in loop is expensive operation.


The second one on the other hand:

map.put("two", "world");//2

will re-use the interned string literal from the String Literal Pool. The String literal pool is a collection of references to string objects created on heap. Java automatically interns the String literals, so that multiple usage of the same string literal doesn't create a new string object everytime. When a string literal is encountered first time, an object for it is created on the heap, and a reference to that object is stored on the string literal pool.

On subsequent use of the same string literal, the same string reference from the literal pool is used instead of creating a new string object on heap. And this is safe, given that Strings are immutable, we can share reference to the same String object. So, certainly this is better approach.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

You should do

map.put("two", "world"); as #2 approach would create new string every time without looking for already present string in the pool as Oscar mentioned.

anubhava
  • 761,203
  • 64
  • 569
  • 643
Rachel
  • 100,387
  • 116
  • 269
  • 365