Campbell Ritchie wrote:That blog is suggesting bad programming practice, viz inspecting the implementation rather than the public interface.
Good point. We shouldn't have to care. However, in this particular case, it can be worth knowing these details, though the actual use case is quite rare.
If you take a small substring of a large String, and that substring lives on long after you're done with the larger String, you can end up wasting memory. I thought that substring()'s docs used to even mention it, but maybe I first saw it somewhere else. I've never actually run across this in a dozen or so years of Java programming, but if it did happen, and you didn't know about this particular String implementation detail, you could be scratching your head for a while trying to figure out why you're running out of memory.
The simple work around is to do
rather than
because then the new String will get its own backing array.
However, this is a pointless premature optimization in the hugely vast majority of cases. Only when you know for certain--or better yet have measured with a profiler--that you'll be wasting significant memory should you do this.