0

How does substring method work internally and how can it create memory issue ?

How can we solve it?

assylias
  • 321,522
  • 82
  • 660
  • 783
Deen John
  • 3,522
  • 4
  • 29
  • 32
  • 1
    Because `substring` returns a new String and it's unclear what you're asking, please put more efforts when asking a question. – Maroun Jan 22 '15 at 12:36
  • 1
    So, which kind of memory issue is reported? – qwerty_so Jan 22 '15 at 12:36
  • Have a look here. http://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/ In Java < 7 there might be situations where more memory is allocated then needed from a application logic point of view. – SubOptimal Jan 22 '15 at 12:37
  • Related: http://stackoverflow.com/questions/14193571/how-does-java-store-strings-and-how-does-substring-work-internally?rq=1 – Thilo Jan 22 '15 at 12:41

1 Answers1

1

Prior to Java 7 udate 6, substring used to return a view on the original string. So imagine you had a String of 1,000,000 characters and called s.substring(0, 1) because you are only interested in the first character, the original string would have stayed in memory.

Since Java 7u6 substring returns a new string which prevents that issue.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • 1
    Of course, if you needed 300 views of 100,000 of that 1,000,000 characters, the new version might make you sad. Can't make everyone happy... – Thilo Jan 22 '15 at 12:40
  • @assylias : that's exactly what i want to know . how did they solved the unnecessary memory allocation in next version – Deen John Jan 22 '15 at 12:49
  • Interesting. I knew about the issue and knew I had to enclose the substring in a 'new String()', if I want to release the original string. I didn't know this behaviour was changed in Java 7. So, how can I avoid much memory usage, if I do much substrings on an original String now? – Mnementh Jan 22 '15 at 12:49
  • @DeenJohn They just create a new string instead of sharing the underlying `char[]`. – assylias Jan 22 '15 at 12:51
  • @assylias: thanks, that's helpful :) – Deen John Jan 22 '15 at 12:54