File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes substring (String class) - Memory Leak (Java) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "substring (String class) - Memory Leak (Java)" Watch "substring (String class) - Memory Leak (Java)" New topic

substring (String class) - Memory Leak (Java)

Steven Rodeo
Ranch Hand

Joined: Mar 06, 2008
Posts: 72

Apologies if this question has been beaten to submission :-). I saw few online articles suggesting that the subString (method of String Class) returns a String backed by the same char[] array that the original String is built on ?.

Honestly, I was looking at the internal implementation of String (jdk7) and seems like this is not the case ?.

Thanks Much!
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

It used to. I think it just got changed in Java 7.

It probably stemmed from the early days of Java when object creation and GC was a lot more expensive than it is now. Probably most substring() calls lead to strings that are not a tiny portion of a huge string and/or are relatively short-lived, so the cases where the "leak" would matter were pretty rare, while the memory management overhead savings were comparatively large, thus making it worth it.

Now, presumably, since the overhead associated with object creation and GC is much diminished, the designers probably figured it's no longer a worthwhile savings.
Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

Yes, this was resolved in 7u6.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
I agree. Here's the link:
subject: substring (String class) - Memory Leak (Java)
jQuery in Action, 3rd edition