在之前的博客中,分别实现了基于数组的栈和基于链表的栈。
下面来使用代码对比我们自己实现的栈的性能差异:
private static double testStack(Stack<Integer> s, int opCnt) {
long startTime = System.nanoTime();
for (int i = 0; i < opCnt; i++) {
s.push(i);
}
for (int i = 0; i < opCnt; i++) {
s.pop();
}
long endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0;
}
上面的代码实现:对栈进行opCnt次入栈和出栈操作,记录所消耗的时间。(注:nonoTime的单位是ns,将结果转换为s,除以10的9次方)
首先将opCnt设置为10 0000 来看看性能差异:
public static void main(String[] args) {
ArrayStack<Integer> arrayStack = new ArrayStack<Integer>();
LinkedStack<Integer> linkedStack = new LinkedStack<Integer>();
int opCnt = 100000;
double time1 = test