RFR: 8361018: Eliminate unnecessary buffering and encoding conversion in BufferedWriter
ExE Boss
duke at openjdk.org
Mon Jun 30 04:54:50 UTC 2025
On Fri, 27 Jun 2025 16:48:40 GMT, Shaojin Wen <swen at openjdk.org> wrote:
> BufferedWriter -> OutputStreamWriter -> StreamEncoder
>
> In this call chain, BufferedWriter has a char[] buffer, and StreamEncoder has a ByteBuffer. There are two layers of cache here, or the BufferedWriter layer can be removed. And when charset is UTF8, if the content of write(String) is LATIN1, a conversion from LATIN1 to UTF16 and then to LATIN1 will occur here.
>
> LATIN1 -> UTF16 -> UTF8
>
> We can improve BufferedWriter. When the parameter Writer instanceof OutputStreamWriter is passed in, remove the cache and call it directly. In addition, improve write(String) in StreamEncoder to avoid unnecessary encoding conversion.
src/java.base/share/classes/java/io/BufferedWriter.java line 244:
> 242: }
> 243:
> 244: private static abstract sealed class BufferedImpl permits WriterImpl, OutputStreamWriterImpl {
No need to explicitly list the permitted subclasses when in the same compilation unit:
Suggestion:
private static abstract sealed class BufferedImpl {
src/java.base/share/classes/java/io/BufferedWriter.java line 468:
> 466: }
> 467:
> 468: public void close() throws IOException {
These implement the package‑private methods from `BufferedImpl`, so they probably should have `@Override` and don’t need to be `public`:
Suggestion:
@Override
void flushBuffer() throws IOException {
os.flushBuffer();
}
@Override
void write(int c) throws IOException {
os.write(new char[] {(char) c});
}
@Override
void write(char[] cbuf, int off, int len) throws IOException {
os.write(cbuf, off, len);
}
@Override
void write(String s, int off, int len) throws IOException {
os.write(s, off, len);
}
@Override
void flush() throws IOException {
os.flush();
}
@Override
void close() throws IOException {
Same applies to the regular `WriterImpl`.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/26022#discussion_r2173989119
PR Review Comment: https://git.openjdk.org/jdk/pull/26022#discussion_r2173990102
More information about the core-libs-dev
mailing list