Created
December 18, 2018 16:17
-
-
Save iafsilva/582144d87cbc31d3b035f9be6a0d4bb4 to your computer and use it in GitHub Desktop.
Benchmark for testing addition and iteration of elements into a list vs a set
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.*; | |
import java.util.concurrent.*; | |
class Main { | |
public static void main(String[] args) { | |
Set<Integer> s = Collections.newSetFromMap(new ConcurrentHashMap<Integer, Boolean>()); | |
CopyOnWriteArrayList<Integer> a = new CopyOnWriteArrayList<>(); | |
int total1 = 0; | |
int total2 = 0; | |
long ts = System.currentTimeMillis(); | |
for (Integer i = 0; i<100000; i++) { | |
a.add(i); | |
} | |
System.out.println("Array add " + a.size() + " elements in " + Long.toString(System.currentTimeMillis() - ts) + "ms"); | |
ts = System.currentTimeMillis(); | |
for (Integer i = 0; i<100000; i++) { | |
s.add(i); | |
} | |
System.out.println("Set add " + s.size() + " elements in " + Long.toString(System.currentTimeMillis() - ts) + "ms"); | |
ts = System.currentTimeMillis(); | |
for (Integer i: a) { | |
total1 += i; | |
} | |
System.out.println("Array Iter " + Long.toString(System.currentTimeMillis() - ts) + "ms"); | |
ts = System.currentTimeMillis(); | |
for (Integer i: s) { | |
total2 += i; | |
} | |
System.out.println("Set Iter " + Long.toString(System.currentTimeMillis() - ts) + "ms" ); | |
System.out.println("END= Array sum total: " + total1 + "; Set sum total:" + total2 + ";"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Array add 100000 elements in 3984ms
Set add 100000 elements in 34ms
Array Iter 12ms
Set Iter 16ms
END= Array sum total: 704982704; Set sum total:704982704;
Tested on Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz