Created
February 24, 2016 19:01
-
-
Save fnl/cfaa82ab59edd0409aa6 to your computer and use it in GitHub Desktop.
Comparing Java HashSet, TreeSet, and LinkedHashSet performance.
This file contains hidden or 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.*; | |
public class test{ | |
// Conclusion | |
// use HashSet... | |
// ...unless you have few accesses and mostly only build them, in which case LinkedHashSet is faster | |
// ...and only use TreeSet when you need the order | |
final static int size = 500; | |
final static int accesses = 10; | |
final static int repeats = 1000; | |
public static void doLoop(Set<Integer> testSet) { | |
for (int i = 0; i < size; i++) { | |
testSet.add(i); | |
} | |
for (int i = 0; i < accesses; i++) { | |
testSet.contains(i%size); | |
} | |
for (int i = 0; i < size; i++) { | |
testSet.remove(i); | |
} | |
} | |
public static void main(String[] args) { | |
Set<Integer> testSet; | |
long startTime = System.nanoTime(); | |
for (int j = 0; j < repeats; j++) { | |
doLoop(new HashSet<Integer>()); | |
} | |
long endTime = System.nanoTime(); | |
long duration = endTime - startTime; | |
System.out.println(" HashSet: " + duration/repeats); | |
startTime = System.nanoTime(); | |
for (int j = 0; j < repeats; j++) { | |
doLoop(new TreeSet<Integer>()); | |
} | |
endTime = System.nanoTime(); | |
duration = endTime - startTime; | |
System.out.println(" TreeSet: " + duration/repeats); | |
startTime = System.nanoTime(); | |
for (int j = 0; j < repeats; j++) { | |
doLoop(new LinkedHashSet<Integer>()); | |
} | |
endTime = System.nanoTime(); | |
duration = endTime - startTime; | |
System.out.println("LinkedHashSet: " + duration/repeats); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment