On 6/20/19 2:39 PM, Kasper Nielsen wrote:
If you allowed a two-time pass of the primitive array you could
actually create a version that only allocated the actual String and
backing array.
I tried implementing it
https://gist.github.com/kaspernielsen/62e4eedffdb395228777925551a45e7f
And got a 30-40 % performance increase.
This is nice and garbage-free.
This method is not very performance critical I think (unless someone is
using it to format int[] into JSON for example), so I don't know whether
optimizing it is that important. OTOH the optimized code is not that
difficult to understand, so why not? I would also add overflow checks
when computing the length of resulting byte[]. First I would pre-check
the length of passed in int[] array (it must be less than
Integer.MAX_VALUE / 3), then checking for negative size after each
addition of element length, throwing OOME if overflow happens. Then I
would re-check if the performance is still favorable and see if the
resulting method is not too complicated to understand after all.
Regards, Peter
ToString2.toStringExisting 1 avgt 5 16.855 ± 0.960 ns/op
ToString2.toStringExisting 10 avgt 5 79.247 ± 3.142 ns/op
ToString2.toStringExisting 100 avgt 5 814.197 ± 46.062 ns/op
ToString2.toStringExisting 1000 avgt 5 15288.172 ± 1649.338 ns/op
ToString2.toString2Pass 1 avgt 5 13.671 ± 0.142 ns/op
ToString2.toString2Pass 10 avgt 5 54.090 ± 0.724 ns/op
ToString2.toString2Pass 100 avgt 5 513.508 ± 6.063 ns/op
ToString2.toString2Pass 1000 avgt 5 9189.950 ± 47.059 ns/op
ToString2.toStringExisting:·gc.alloc.rate.norm 1 avgt
5 80.000 ± 0.001 B/op
ToString2.toStringExisting:·gc.alloc.rate.norm 10 avgt
5 160.000 ± 0.001 B/op
ToString2.toStringExisting:·gc.alloc.rate.norm 100 avgt
5 1664.000 ± 0.001 B/op
ToString2.toStringExisting:·gc.alloc.rate.norm 1000 avgt
5 23536.006 ± 0.001 B/op
ToString2.toString2Pass:·gc.alloc.rate.norm 1 avgt
5 48.000 ± 0.001 B/op
ToString2.toString2Pass:·gc.alloc.rate.norm 10 avgt
5 120.000 ± 0.001 B/op
ToString2.toString2Pass:·gc.alloc.rate.norm 100 avgt
5 840.000 ± 0.001 B/op
ToString2.toString2Pass:·gc.alloc.rate.norm 1000 avgt
5 9848.004 ± 0.001 B/op
Don't know if it is something worth adding?
/Kasper