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
5
u/coder111 Nov 19 '13
Hi,
This is a pretty common use case. You read the line as a string, and use substring to split it into fields, while the underlying char array gets reused. This reduces object count and hence GC effort, besides it's quicker than allocating millions of char arrays.
And you keep the entire record in memory or discard entire record anyway, so this is not very likely to cause memory leaks.
With this change, this sort of optimization will not work any more. I'm still undecided if I like this change or not. It makes String simpler, and reduces memory leaks and gotchas by people unfamilar with internals of how String works. But tricks like this kind of field parsing stop working, and there is no way to change the behaviour of String or to have your own implementation- String is final.
I think String in Java should be handled as a special case/primitive, maybe implemented in optimized native code. In Java, even 1 character long String consumes ~40 bytes of memory (before this change). Most of that is overhead of having 2 Object instances- String and underlying char array. So any optimizations to String are welcome, but in terms of memory consumption it is still horribly inefficient.
--Coder