Skip to content

Instantly share code, notes, and snippets.

@kitsook
Created August 2, 2022 03:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kitsook/1f0b04e641e633b7b7dae42d421e3e6d to your computer and use it in GitHub Desktop.
Save kitsook/1f0b04e641e633b7b7dae42d421e3e6d to your computer and use it in GitHub Desktop.
Simulate the performance issue of Collections.shuffle
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;
public class ShufflePerformance {
private static final int PARALLELISM = 4;
private static final int LIST_SIZE = 100;
private static final int TRIAL_COUNT = 10_000_000;
private static List<Integer> initBoxesByRandInsert() {
List<Integer> boxes = new ArrayList<>(LIST_SIZE);
Random rand = new Random();
boxes.add(0);
for (int i = 1; i < LIST_SIZE; i++) {
boxes.add(rand.nextInt(boxes.size()), i);
}
return boxes;
}
private static List<Integer> initBoxesByShuffle() {
List<Integer> boxes = new ArrayList<>(LIST_SIZE);
for (int i = 0; i < LIST_SIZE; i++) {
boxes.add(i);
}
Collections.shuffle(boxes);
return boxes;
}
public static void main(String[] args) throws Exception {
ForkJoinPool customThreadPool = new ForkJoinPool(PARALLELISM);
try {
long winCount = customThreadPool.submit(() ->
IntStream.rangeClosed(1, PARALLELISM)
.parallel()
.map(_i -> IntStream.rangeClosed(1, TRIAL_COUNT / PARALLELISM)
.map(_j -> {
// comment / uncommnt to choose which approach to use
List<Integer> boxes = initBoxesByShuffle();
//List<Integer> boxes = initBoxesByRandInsert();
// dummy calculation to avoid any optimization to skip the list generation
return boxes.stream().reduce(0, Integer::sum);
})
.reduce(0, Integer::sum))
.reduce(0, Integer::sum)
).get();
} finally {
customThreadPool.shutdown();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment