diff --git a/elastiknn-api4s/src/main/java/com/klibisz/elastiknn/api/FloatArrayBuffer.java b/elastiknn-api4s/src/main/java/com/klibisz/elastiknn/api/FloatArrayBuffer.java index 274e84178..3e8dec688 100644 --- a/elastiknn-api4s/src/main/java/com/klibisz/elastiknn/api/FloatArrayBuffer.java +++ b/elastiknn-api4s/src/main/java/com/klibisz/elastiknn/api/FloatArrayBuffer.java @@ -36,7 +36,9 @@ public void append(float f) { } public float[] toArray() { - nextInitialCapacity = Math.min(maxInitialCapacity, Math.max(minInitialCapacity, index)); + if (nextInitialCapacity != index) { + nextInitialCapacity = Math.min(maxInitialCapacity, Math.max(minInitialCapacity, index)); + } if (this.array.length == index) { return this.array; } else { diff --git a/elastiknn-jmh-benchmarks/src/main/scala/com/klibisz/elastiknn/jmhbenchmarks/FloatArrayBufferBenchmarks.scala b/elastiknn-jmh-benchmarks/src/main/scala/com/klibisz/elastiknn/jmhbenchmarks/FloatArrayBufferBenchmarks.scala new file mode 100644 index 000000000..c620c4bfe --- /dev/null +++ b/elastiknn-jmh-benchmarks/src/main/scala/com/klibisz/elastiknn/jmhbenchmarks/FloatArrayBufferBenchmarks.scala @@ -0,0 +1,49 @@ +package com.klibisz.elastiknn.jmhbenchmarks + +import com.klibisz.elastiknn.api.FloatArrayBuffer +import org.openjdk.jmh.annotations._ + +import scala.collection.mutable.ArrayBuffer +import scala.util.Random + +@State(Scope.Benchmark) +class FloatArrayBufferBenchmarksState { + implicit private val rng: Random = new Random(0) + val lst768 = (0 until 768).map(_ => rng.nextFloat()).toList +} + +class FloatArrayBufferBenchmarks { + + @Benchmark + @BenchmarkMode(Array(Mode.Throughput)) + @Fork(value = 1) + @Warmup(time = 5, iterations = 1) + @Measurement(time = 5, iterations = 1) + def scalaAppendFixedInitialSize(state: FloatArrayBufferBenchmarksState): Int = { + val buf = new ArrayBuffer[Float]() + state.lst768.foreach(buf.append) + buf.toArray.length + } + + @Benchmark + @BenchmarkMode(Array(Mode.Throughput)) + @Fork(value = 1) + @Warmup(time = 5, iterations = 1) + @Measurement(time = 5, iterations = 1) + def scalaAppendKnownInitialSize(state: FloatArrayBufferBenchmarksState): Int = { + val buf = new ArrayBuffer[Float](768) + state.lst768.foreach(buf.append) + buf.toArray.length + } + + @Benchmark + @BenchmarkMode(Array(Mode.Throughput)) + @Fork(value = 1) + @Warmup(time = 5, iterations = 1) + @Measurement(time = 5, iterations = 1) + def customAppend(state: FloatArrayBufferBenchmarksState): Int = { + val buf = new FloatArrayBuffer() + state.lst768.foreach(buf.append) + buf.toArray.length + } +}