我读到在TreeSet中的搜索时间是log(N)的量级,而在HashSet中的搜索时间是1(常量)的量级.现在,为了在程序中测试这一点,我编写了一个Java程序.
import java.util.TreeSet;
import java.util.Random;
public class SearchSpeed {
int totalElements, target;
Set<Integer> hashSet, treeSet;
Random r;
// parameterized constructor
SearchSpeed(int totalElements){
this.totalElements = totalElements;
r = new Random();
hashSet = new HashSet<>();
treeSet = new TreeSet<>();
}
// populating the sets and selecting the target element
void populateSets(){
hashSet.clear();
treeSet.clear();
int num, count = 0;
while(hashSet.size() != totalElements){
num = r.nextInt();
hashSet.add(num);
treeSet.add(num);
count++;
if(count == 5000){ // picking the 5000th element as the target element
target = num;
}
}
}
// searching the target element in HashSet
long searchHash(){
long initialTime = System.nanoTime();
hashSet.contains(target);
long finalTime = System.nanoTime();
return finalTime - initialTime;
}
// searching the target element in TreeSet
long searchTree(){
long initialTime = System.nanoTime();
treeSet.contains(target);
long finalTime = System.nanoTime();
return finalTime - initialTime;
}
public static void main(String[] args) {
SearchSpeed ss = new SearchSpeed(10000);
long hashTime = 0, treeTime = 0;
for(int i = 0; i < 1000; i++){
ss.populateSets();
hashTime += ss.searchHash();
treeTime += ss.searchTree();
}
double avgTreeTime = treeTime/1000.0;
double avgHashTime = hashTime/1000.0;
System.out.printf("Time taken by TreeSet MINUS Time Taken by HashSet = %.4f nanoseconds\n",avgTreeTime - avgHashTime);
}
}
在多次运行这个程序后,我得到了以下结果:
输出1:树集所用时间减go 哈希集所用时间=105.6000纳秒
输出2:树集所用时间减go 哈希集所用时间=99.1000纳秒
输出3:树集所用时间减go 哈希集所用时间=36.8000纳秒
输出4:树集所用时间减go 哈希集所用时间=50.6000纳秒
输出5:树集所用时间减go 哈希集所用时间=-30.4000纳秒
我原本预计时间差会更大一些,但在某些情况下,时间差低至36纳秒,在某些情况下甚至为负值.
这是我应该期待的吗?还是我在编写程序时遗漏了什么?