Why is the initial capacity to the ArrayList constructor commented out. IIRC, the default capacity is 10, so in your test case, you are getting hit with a reallocation each time. What is the metrics if you do not comment out STRINGS.length to the ArrayList ctor?
--ewh On Sat, May 31, 2025, 9:16 AM esaulpaugh (via GitHub) <g...@apache.org> wrote: > > esaulpaugh commented on PR #212: > URL: https://github.com/apache/ant/pull/212#issuecomment-2925232549 > > I have not faced a performance issue but I discovered this trick while > optimizing a String parser in one of my projects. It performs better in > microbenchmarks compared to building an `ArrayList`. I suggested it to gson > as well: https://github.com/google/gson/pull/2734 > > On corretto-11.0.27 aarch64: > > ``` > Benchmark Mode Cnt Score Error Units > Measure.arr avgt 14 17.527 ± 0.435 ns/op > Measure.list avgt 14 44.013 ± 27.030 ns/op > ``` > > On graalvm-jdk-24+36.1 (24.2.0) aarch64: > > ``` > Benchmark Mode Cnt Score Error Units > Measure.arr avgt 14 9.795 ± 0.173 ns/op > Measure.list avgt 14 41.321 ± 3.544 ns/op > ``` > > ```java > @State(Scope.Benchmark) > @Fork(2) > @BenchmarkMode(Mode.AverageTime) > @Warmup(iterations = 7, time = 500, timeUnit = TimeUnit.MILLISECONDS) > @Measurement(iterations = 7, time = 500, timeUnit = > TimeUnit.MILLISECONDS) > @OutputTimeUnit(TimeUnit.NANOSECONDS) > public class Measure { > > private static final String[] STRINGS = { null, "", "00", "\0", > "...", null, "H", "ab", "+", "UUU", null, null, "5\t5" }; > > @Benchmark > public void list(Blackhole blackhole) { > ArrayList<String> list = new ArrayList<>(/* STRINGS.length */); > for (String s : STRINGS) { > if (s != null) { > list.add(s); > } > } > blackhole.consume(list.toArray(new String[0])); > } > > @Benchmark > public void arr(Blackhole blackhole) { > String[] arr = new String[STRINGS.length]; > int i = 0; > for (String s : STRINGS) { > if (s != null) { > arr[i++] = s; > } > } > blackhole.consume(Arrays.copyOf(arr, i)); > } > } > ``` > > It's unlikely that this change alone would make a noticeable difference > to users, but small changes can add up eventually, in my experience. > > > -- > This is an automated message from the Apache Git Service. > To respond to the message, please log on to GitHub and use the > URL above to go to the specific comment. > > To unsubscribe, e-mail: dev-unsubscr...@ant.apache.org > > For queries about this service, please contact Infrastructure at: > us...@infra.apache.org > > > --------------------------------------------------------------------- > To unsubscribe, e-mail: dev-unsubscr...@ant.apache.org > For additional commands, e-mail: dev-h...@ant.apache.org > >