4 ms·
Even with the surrogate pairs, Java's choice strikes a compromise between the memory efficiency of UTF-8 and the performance of fixed size code points. Most of
by nearbuy 6y ago
Even with the surrogate pairs, Java's choice strikes a compromise between the memory efficiency of UTF-8 and the performance of fixed size code points. Most of the string methods work as if all characters are two bytes. So if, for example, you have a string composed entirely of 4 byte emojis, charAt(10) would return the first part of the 6th emoji, not the 11th emoji.
For many cases, strings won't use any characters outside of UCS-2. In these cases, programmers gain the performance advantages of fixed sized characters without worrying about the downsides of surrogate pairs. It doesn't have the small memory footprint of UTF-8, but one could argue that if memory size is really important and fixed size characters are not, you're better off using in-memory compression for your strings, which will beat UTF-8.
If you are using characters outside of UCS-2, then Java's string methods are a potential source of confusion and bugs. There's always a trade-off, right?