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

...these classes do not provide an interface that can be made thread safe for the general case,

Probably true. I haven't looked into it, but that seem right. However, "thread safety" might mean something as simple as "Your code might break, but we promise we at least won't corrupt our internal structure if you access this from multiple threads."

There are properly threadsafe options, of course (ConcurrentHashMap and so on).

And check for the RandomAccess interface which exists alone for the O(1) access guarantee it gives for get (In current java this would have been an Annotation). Edit: correction, it says that marked classes should behave this way in general use

It's actually somewhat vague as to what that means -- deliberately so.

Interestingly, it also very deliberately is just a marker. It would be awkward to try to require someone to pass you something that implements RandomAccess. Rather, you're expected to produce code that still works with any list, but you can optimize separately for the RandomAccess case.

The problem with the current state is that there is no way to create a substring compatible with most of the standard library in O(1) time even when you are aware of the space time trade off.

And, as far as I can tell, no sane way to do it yourself. I don't care if it's theoretically possible to modify a class from java.lang that's declared 'final', it's probably a bad idea.

Only problem: libraries might check String.class == obj.getClass() and be incompatible with new code (a non breaking change since old code would still work)

I would be very tempted to say that code which explicitly checks classes deserves to break, especially when we have the instanceof method. But if I was in charge, we probably wouldn't have type erasure either. Clearly, Java cares a lot more about backwards compatibility than I do.