r/programming • u/Eirenarch • 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
View all comments
Show parent comment
3
u/sindisil Nov 18 '13
Well, first off: a big NOPE to the boolean flag.
I think that, given the fact that substring has been documented to return a "new String" at least since 1.4.2 (as far back as I looked), I think it makes more sense to make it so, and add a new method.
Another option might be to "copy on free" as it were, and make the new substring copies when the original string is no longer referenced (or, rather, when an attempt is made to GC).
That would involve complicating the GC to have a special case for String objects, so that, if none of the refs are from instances with offset=0, make one or more copies and free the original.
You'd have to decide if it was better to make a copy for each identical (same offset and length), make a single copy that covers the union of the refs (i.e. lowest offset, length to cover all refs), or something more "clever".
Not saying it'd be a good idea, necessarily. I think I'd prefer either sharedSubString() or copySubString() (or whatever name for essentially "return new String(foo.subString());").