r/programming • • Nov 18 '13

TIL Oracle changed the internal String representation in Java 7 Update 6 increasing the running time of the substring method from constant to N

http://java-performance.info/changes-to-string-java-1-7-0_06/
1.4k Upvotes

354 comments sorted by

View all comments

Show parent comment

2

u/KimJongIlSunglasses Nov 18 '13

Question: why is a substring operation which copies the whole string able to run in constant time, but other cases are O(n)?

Do you not still need to allocate new memory for the underlying char array and create the same new object instances in both cases?

Or is substring of the entire string equivalent to basically returning a reference to the original string?

4

u/KillerCodeMonky Nov 18 '13

The second option. Since Java strings are immutable, copying the entire string means you can just reuse the same character array. This is the same principle that allowed the substring indexing shortcut to work in the first place.

3

u/cowinabadplace Nov 18 '13

Your last sentence is exactly it.

You have a character array and an offset. A substring, is just the same array with different offsets delimiting. This is explained in the article. You don't copy the array. You reuse it.