RFR: 8358533: Improve performance of java.io.Reader.readAllLines

Chen Liang liach at openjdk.org
Wed Jun 18 02:42:38 UTC 2025


On Wed, 18 Jun 2025 00:04:37 GMT, Brian Burkhalter <bpb at openjdk.org> wrote:

> Replaces the implementation `readAllCharsAsString().lines().toList()` with reading into a temporary `char` array which is then processed to detect line terminators and copy non-terminating characters into strings which are added to the list.

src/java.base/share/classes/java/io/Reader.java line 453:

> 451:         char[] cb = new char[TRANSFER_BUFFER_SIZE];
> 452:         int pos = 0;
> 453:         List<String> lines = new ArrayList<String>();

Suggestion:

        List<String> lines = new ArrayList<>();

src/java.base/share/classes/java/io/Reader.java line 455:

> 453:         List<String> lines = new ArrayList<String>();
> 454: 
> 455:         StringBuilder sb = new StringBuilder(82);

Is there a reason for this pre-allocation? If the whole content is smaller than 8192 in size, this allocation would be redundant because we are going through the string constructor path.

src/java.base/share/classes/java/io/Reader.java line 499:

> 497:             }
> 498: 
> 499:             if (!stringAdded) {

Can we change the maintenancce of `stringAdded` condition to a check `sb.length() == 0`?

Edit: No, we need to check empty lines.

-------------

PR Review Comment: https://git.openjdk.org/jdk/pull/25863#discussion_r2153505559
PR Review Comment: https://git.openjdk.org/jdk/pull/25863#discussion_r2153509369
PR Review Comment: https://git.openjdk.org/jdk/pull/25863#discussion_r2153518622


More information about the core-libs-dev mailing list