Created
August 2, 2022 03:59
-
-
Save kitsook/1f0b04e641e633b7b7dae42d421e3e6d to your computer and use it in GitHub Desktop.
Simulate the performance issue of Collections.shuffle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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