On Thu, 20 Jun 2019 at 21:31, Peter Levart <peter.lev...@gmail.com> wrote: > > > 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.
You actually don't need to check on each element. Use a long instead of an int to sum up all sizes. And then just check once, which should not effect performance. But implementing it do require adding a public method to (preferable) every primitive wrapper. As Arrays is in java.util and needs access to package private methods (stringSize() and getChars()) in each wrapper. One way to do it would be to add: class Integer public static String toArrayString(int... ints) I do actually occasionally miss such a method with varargs sometimes. I also think I would let the method throw an NPE on null instead of returning "null". And change the implementation of Arrays.toString to public static String toString(int[] a) { if (a == null) return "null"; return Integer.toStringArray(a); } /Kasper