Игорь Рыбаков Игорь Рыбаков - 6 months ago 43
Java Question

The fastest way to add elements in set collection

I have a task to add in treeset > 10000000 elements that are sequence.

If I use

for (long index = 0; index < 10000000; index++)
{
result.add(index);
}


It takes 8083 ms. Is there any solution to increase the performance of this task?

https://github.com/cyberterror/TestRanges

P.S. The fastest way at the moment is:
List<Integer> range = IntStream.range(0, 10000000).boxed().collect(Collectors.toList());
with result of ~ 370 ms

Answer

Try HPPC: High Performance Primitive Collections for Java

License: Apache License 2.0

<dependency>
  <groupId>com.carrotsearch</groupId>
  <artifactId>hppc</artifactId>
  <version>0.7.1</version>
</dependency>

LongHashSet executes in 1190ms:

LongSet result = new LongHashSet();
for (Long index = 0L; index < 10000000L;) {
  result.add(index++);
}

LongScatterSet executes in 850ms:

LongSet result = new LongScatterSet();
for (Long index = 0L; index < 10000000L;) {
  result.add(index++);
}
Comments