Hi,
On 6/20/19 10:50 AM, Kasper Nielsen wrote:
Hi,
On Wed, 19 Jun 2019 at 14:12, Сергей Цыпанов <sergei.tsypa...@yandex.ru> wrote:
Hello,
in JDK code base we have many places (mainly in j.u.Arrays) where we convert
array to String using verbose constructions with StringBuilder.
As far as we have got StringJoiner for a long time we can use it making the
code more simple.
It may make the code simpler, but it also comes with a hefty
performance penalty, taking twice as long in most cases compared to
the existing code.
A quick benchmark toString'ing int arrays of size 1,10,100,1000
Benchmark (size) Mode Cnt Score Error Units
ToString2.toStringExisting 1 avgt 5 16.675 ± 0.327 ns/op
ToString2.toStringExisting 10 avgt 5 78.467 ± 1.373 ns/op
ToString2.toStringExisting 100 avgt 5 801.956 ± 7.517 ns/op
ToString2.toStringExisting 1000 avgt 5 14944.235 ± 155.393 ns/op
ToString2.toStringSuggested 1 avgt 5 35.053 ± 0.533 ns/op
ToString2.toStringSuggested 10 avgt 5 222.043 ± 10.157 ns/op
ToString2.toStringSuggested 100 avgt 5 2150.948 ± 13.285 ns/op
ToString2.toStringSuggested 1000 avgt 5 23411.264 ± 201.721 ns/op
/Kasper
StringJoiner may be faster if you already have String objects at hand,
since it is able to exactly pre-size the target array and need not
copy/resize it later, but if you append primitive types, then creating
intermediate String objects referenced from a data structure - the
StringJointer (so they can not be scalarized by JIT) is contra-productive.
An interesting test would be to run Kasper's JMH benchmark with "-prof
gc" option. I think it will show more garbage created per call too.
Regards, Peter