玩转数据结构(五)数组栈和链表栈性能对比

本文对比了基于数组和链表实现的栈在不同操作次数下的性能差异。在opCnt从10,0000到1,000,0000逐步增加的过程中,虽然两者的时间复杂度均为O(1),但在大量操作下,由于链表栈的new操作,arrayStack的性能优于linkedStack。" 126865596,7963447,vue-cli3: 移除生产环境console.log,"['vue.js', '前端开发', 'Webpack', 'Babel']
摘要由CSDN通过智能技术生成

在之前的博客中,分别实现了基于数组的栈和基于链表的栈。

下面来使用代码对比我们自己实现的栈的性能差异:

 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值