-
Notifications
You must be signed in to change notification settings - Fork 361
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
Comments
This was referenced Oct 16, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
aStringBuilder
.PrintStream
implements a method likeprint(obj: AnyRef)
that can thus accept aStringBuilder
:scala-native/javalib/src/main/scala/java/io/PrintStream.scala
Line 168 in 63d0709
However, it will call
String.valueOf(obj: AnyRef)
that will trigger under the hoodStringBuilder.toString
implemented inAbstractStringBuilder
.This means that currently, printing a
StringBuilder
to a console or a file, will allocate a newString
systematically (even if theStringBuilder
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 theStringBuilder.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: #2905It means that currently it will not only create a new
String
object instance, but it will also copy the underlyingArray
systematically.The text was updated successfully, but these errors were encountered: