Java Language Java Pitfalls - Performance Issues Pitfall - Calling 'new String(String)' is inefficient

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Using new String(String) to duplicate a string is inefficient and almost always unnecessary.

  • String objects are immutable, so there is no need to copy them to protect against changes.
  • In some older versions of Java, String objects can share backing arrays with other String objects. In those versions, it is possible to leak memory by creating a (small) substring of a (large) string and retaining it. However, from Java 7 onwards, String backing arrays are not shared.

In the absence of any tangible benefit, calling new String(String) is simply wasteful:

  • Making the copy takes CPU time.
  • The copy uses more memory which increases the application's memoru footprint and / or increases GC overheads.
  • Operations like equals(Object) and hashCode() can be slower if String objects are copied.


Got any Java Language Question?