4

I have a custom CharSequence implementation and want to implement a toString with the minimum amount of allocations. And I want it to work in Java 8 and newer versions.

I know I can use a StringBuilder pre-alocated with the (known) length of my sequence and insert one char at a time. But StringBuilder#toString will eventually call some String constructor that will copy the builder array. I want to avoid creating this additional array.

My goal was to create a char[] directly and pass to a non-copying String constructor, and I know I can use SharedSecrets.getJavaLangAccess().newStringUnsafe() to do that in Java 8, but it has been removed in Java 11. I know that Strings in newer versions are no longer backed by char[].

Is there a supported way (Java 8+) of creating a String, char-by-char without creating intermediary objects?

Michael
  • 41,989
  • 11
  • 82
  • 128
Juan Lopes
  • 10,143
  • 2
  • 25
  • 44
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/197296/discussion-on-question-by-juan-lopes-coverting-charsequence-to-string-without-ad). – George Stocker Jul 31 '19 at 17:01
  • There is no need to “insert one char at a time”. The canonical implementation of a `CharSequence`’s `toString()` method would be `return new StringBuilder(length()).append(this, 0, length()).toString();`. Yes, that’s bearing a copy operation in `StringBuilder.toString()` *in the source code*. Given the presence of a JIT, Escape Analysis and special knowledge about typical string operations within the JVM, it’s very likely that the copying gets optimized away if it ever becomes a HotSpot while any nonstandard trick bears the danger of running unoptimized, hence even worse than naive code. – Holger Aug 07 '19 at 17:21

0 Answers0