0

I want to use regex to parse a huge String largeString.

I am using matcher.group() to obtain substrings of largeString. My question is:

Do matcher.group() returns a new String object, or it only returns a substring reference to largeString ?

As far as I know defining substring only allocates memory for a pointer and 3 int instances. I want to keep largeString for other purposes, so I will prefer keeping substring instances instead of creating new String.

Ivan
  • 149
  • 1
  • 12

1 Answers1

2

This has been answered elsewhere, to some extent.

Since Java 7u6, all substrings are their own String object. So you would not just allocate memory for 16 more bytes, you would allocate memory for a whole String object.

credit: https://stackoverflow.com/a/14193606/1159805

edit: Here's a copy of the proposal explaining why the change was made: http://mail.openjdk.java.net/pipermail/core-libs-dev/2012-May/010257.html

Community
  • 1
  • 1
Eric Dand
  • 1,106
  • 13
  • 37
  • Thanks, I was looking at an old blog post :P That means if I want to save memory, say, I instead store matcher.start() and end()? (just 2 `int`) and call substring method later on the fly? – Ivan Mar 26 '14 at 18:49
  • @Ivan That's right, but remember that calling `substring` *will* create a whole new `String` object. – Eric Dand Mar 26 '14 at 21:42
  • since the `substring` is on the fly, they are used temporarily and will be garbage collected. – Ivan Mar 27 '14 at 06:35