出发点是:即使一个很小,耗时很短的方法,当执行次数够多的时候带来的性能问题也不可小视。
HashMap.containsKey和HashSet.contains优于List.contains.
private static List<String> TestList = new ArrayList<>();
private static Map<String,Boolean> TestMap = new HashMap<>();
private static Set<String> TestSet= new HashSet<>();
private static int TestTimes = 1000*1000*1000;
public static void main(String[] args) {
init();
// System.err.print("List");
// Test(TestList);
// System.err.print("HashMap");
// Test(TestMap.keySet());
System.err.print("HashSet");
Test(TestSet);
}
private static void Test(Collection<String> collect)
{
int count = 0;
long time1 = System.currentTimeMillis();
for (int i = 0; i < TestTimes; i++) {
if(collect.contains("12"))
count++;
}
long time2 = System.currentTimeMillis();
System.err.println(" cost:" + (time2 - time1));
}
private static void init()
{
String a = "1";
String b = "2";
String c = "3";
TestList.add(a);
TestList.add(b);
TestList.add(c);
TestMap.put(a, true);
TestMap.put(b, true);
TestMap.put(c, true);
TestSet.add(a);
TestSet.add(b);
TestSet.add(c);
}
结果:
HashSet cost:1286
HashMap cost:1318
List cost:3948