I need to “shorten” a string in a loop before passing it again and again to be matched by a java.regex.Pattern. Probably a trivial situation for some deeply involved in parsing and text processing.
I am faced with the situation that I have to use:
string=string.substring(shortenHowMuch); //Need to shorten it from the beginning
…which low level developers very well know, that is copying the entire string into another address of the memory. Even with HotSpot’s optimisations in place (which I am aware of), I still need to make sure the code runs in maximum possible performance variant on all possible Java VMs.
Edit:
Later I found out, that my statement above, that it is copying the string, is wrong. So my very question should go “to hell” 🙂 Anyway, read if you like 🙂 .substring does not copy, but instead it does share a reference to a char[], very interesting 🙂
You did not explain what exactly happened when you used StringBuilder so I cannot answer why. But actually you don’t need StringBuilder because String.substring is optimized and it does not copy the internal char array. This is what happens internally