diff --git a/ContainersInDepth/README.md b/ContainersInDepth/README.md index 4691f2d..6bf8c0f 100644 --- a/ContainersInDepth/README.md +++ b/ContainersInDepth/README.md @@ -234,3 +234,10 @@ because an `ArrayList` must create space and copy all its references forward dur **Note**: 1. We can instantiate an abstract class by implementing the abstract method in an anonymous class, like [ListPerformance.java](https://github.com/kean0212/Thinking-In-Java-Notes/blob/master/ContainersInDepth/ListPerformance.java#L22). + +### Choosing between Sets +1. `HashSet` is used for 'insertion' and 'searching'. + +2. `TreeSet` is used for sorted set. + +3. `LinkedHashSet` is for maintaining inserted order. diff --git a/ContainersInDepth/SetPerformance.java b/ContainersInDepth/SetPerformance.java new file mode 100644 index 0000000..a68c825 --- /dev/null +++ b/ContainersInDepth/SetPerformance.java @@ -0,0 +1,61 @@ +import java.util.List; +import java.util.Set; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.HashSet; +import java.util.TreeSet; +import java.util.LinkedHashSet; + +public class SetPerformance { + static List>> tests = new ArrayList<>(); + + static { + tests.add(new Test>("add") { + int test(Set set, TestParam testParam) { + int loops = testParam.loops; + int size = testParam.size; + for (int i = 0; i < loops; ++i) { + set.clear(); + for (int j = 0; j < size; ++j) { + set.add("hello"); + } + } + return loops * size; + } + }); + tests.add(new Test>("contains") { + int test(Set set, TestParam testParam) { + int loops = testParam.loops; + int size = testParam.size * 2; + for (int i = 0; i < loops; ++i) { + for (int j = 0; j < size; ++j) { + set.contains("hello"); + } + } + return loops * size; + } + }); + tests.add(new Test>("iterate") { + int test(Set set, TestParam testParam) { + int loops = testParam.loops * 10; + for (int i = 0; i < loops; ++i) { + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + iterator.next(); + } + } + return loops * set.size(); + } + }); + } + + public static void main(String[] args) { + if (args.length > 0) { + Tester.defaultTestParams = TestParam.array(args); + } + Tester.fieldWidth = 10; + Tester.run(new HashSet(), tests); + Tester.run(new TreeSet(), tests); + Tester.run(new LinkedHashSet(), tests); + } +} \ No newline at end of file