RFC: 8309726: Reader::readString

Markus Karg markus at headcrashing.eu
Sat Jun 10 11:35:52 UTC 2023


By analyzing several existing applications I noticed that many of them need
to read a String from an input source (be it an input stream or a reader),
and there are a lot of solutions applied which all are more or less
suboptimal:

* Files.readString(Path) - Fast, convenient, uses JLA.newStringNoRepl, only
works with files (not with sockets or other sources).
* new String(inputStream.readAllBytes()) - Fast, complex, enforces dealing
with an array in user code, cannot use JLA.newStringNoRepl.
* bufferedReader.lines().collect(StringBuilder::new, StringBuilder::append,
StringBuilder::append).toString(); - Complex, enforces dealing with a stream
in user code, doesn't use JLA.newStringNoRepl.
* reader.transferTo(stringWriter); stringWriter.toString(); - Medium
convient, medium performance, synchronized as it relies on StringBuffer
instead of StringBuilder.
* Custom loop using char[] of various default sizes (some 8k, some 16k, some
configurable) - Slow, complex, doesn't use JLA.newStringNoRepl.
* etc.

Checking back with the particular authors of these applications I noticed
that what they all miss is (a) guidance which solution is "best" (mostly
thinking in speed, but also in reduced GC stress and memory consumption),
(b) something convenient like Files.readString() but working with any reader
implementation, not just with files.

I think we can do better, hence I'd like to propose the introduction of a
new Reader::readString method. The benefits are:
* Guidance. The introduction of this method is a clear signal to all
application programmers to use *this* one by default.
* Convenience. It couldn't be any easier for the caller.
* Performance. OpenJDK committers can optimize it for both, convenience,
speed, reduced GC stress, and memory consumption, at the very same time.
* Optimizable. Each Reader implementation can choose an algorithm fitting
best its own needs, while java.io.Reader itself provides a convenient
default implementation based on a loop over this.read().

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/client-libs-dev/attachments/20230610/9e270a57/attachment.htm>


More information about the client-libs-dev mailing list