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/danielkza Nov 18 '13 edited Nov 18 '13

You're correct that the great majority of people will understand what you meant perfectly, but if one was to be pedantic, saying the running time changed 'to N' can mean:

a) It is exactly N for a length N. Doesn't make much sense due to the lack of time units. b) The lower and upper time bounds are of order N, which means the running time is always the length of the string times a constant, usually denoted Θ(N) in complexity notation.

When what you want is probably O(N) for worst case bound, but only because of something subtle: the JVM probably does not make a copy if it detects you want a substring which is actually the whole string, making it a constant time case.

3

u/HamSandwich53 Nov 18 '13

Ω(N)

Don't you mean Θ(N)? As I understand it, Ω(N) is only a lower bound on the running time to within a constant multiple.

1

u/danielkza Nov 18 '13

You're right, I fixed it, thanks :)

2

u/yayweb21 Nov 18 '13

And it isn't even O(N) where N is the length of the parent string, right? The underlying string is still an indexable array. So the runtime is a function of how many characters your substring requests. The parent is still indexed in constant time.

3

u/isbadawi Nov 18 '13

Right, it's O(N) where N is the length of the substring.

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.

1

u/satayboy Nov 19 '13

Good thing you're not pedantic about your grammar.

0

u/Eirenarch Nov 18 '13

I guess my standard "not a native speaker" excuse won't work this time :(

3

u/danielkza Nov 18 '13

Meh, your title was prefectly fine, I don't think anyone that has even passing familiarity with complexity theory / Big-O notation would fail to understand it.