Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Embrace CharSequence in internal javalib code #2906

Open
david-bouyssie opened this issue Oct 16, 2022 · 0 comments · May be fixed by #2933
Open

Embrace CharSequence in internal javalib code #2906

david-bouyssie opened this issue Oct 16, 2022 · 0 comments · May be fixed by #2933

Comments

@david-bouyssie
Copy link
Contributor

I came accross another interesting finding. It looks like the CharSequence/Appendable interfaces/traits are not systematically used in many places of the javalib. I think it is inherited from initial Java design (see: https://stackoverflow.com/questions/5949926/what-is-the-difference-between-append-and-write-methods-of-java-io-writer).

The good news is that in several places CharSequence could be used instead of (or additionally to) String. This would avoid some possible extra allocations.

I have a simple example: printing to a PrintStream a StringBuilder. PrintStream implements a method like print(obj: AnyRef) that can thus accept a StringBuilder:

def print(obj: AnyRef): Unit = printString(String.valueOf(obj))

However, it will call String.valueOf(obj: AnyRef) that will trigger under the hood StringBuilder.toString implemented in AbstractStringBuilder.
This means that currently, printing a StringBuilder to a console or a file, will allocate a new String systematically (even if the StringBuilder is reused in a loop for instance).

So what is my point? If PrintStream was modified internally to call encoder.append(csq: CharSequence), it would avoid the StringBuilder.toString trip and thus save additional String object allocation.

Remark: this problem is even more important because of the way AbstractStringBuilder.toString currently works, and as described in this other issue: #2905
It means that currently it will not only create a new String object instance, but it will also copy the underlying Array systematically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant