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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With