性能基本数组VS的ArrayList [英] Performance primitive Array vs ArrayList

查看:92
本文介绍了性能基本数组VS的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有性能上的区别,如果我使用一个原始数组,然后重建它添加这样的新元素:

I want to know if there is a difference in performance if I use a primitive array and then rebuild it to add new elements like this:

AnyClass[] elements = new AnyClass[0];

public void addElement(AnyClass e) {
    AnyClass[] temp = new AnyClass[elements.length + 1];
    for (int i = 0; i < elements.length; i++) {
        temp[i] = elements[i];
    }
    temp[elements.length] = e;
    elements = temp;
}

或者如果我只是使用的的ArrayList 添加的元素。

or if I just use an ArrayList and add the elements.

我不能肯定这就是为什么我问,是不是同样的速度,因为一个ArrayList是建立以同样的方式,因为我做了它的基本数组或者是有一个真正的差异和基本数组总是更快,即使我重建它,每次我加一个元素?

I am not certain that is why I ask, is it the same speed because an ArrayList is build in the same way as I did it with the primitive array or is there really a difference and a primitive array is always faster even if I rebuild it everytime I add an element?

推荐答案

的ArrayList以类似的方式工作,而是重建每一次,他们每次达到极限时有翻倍能力。所以,如果你不断地增加它的ArrayList会更快,因为重新创建数组是相当缓慢。
所以,你的实施可以使用较少的内存,如果你不加入,它常常不过至于速度的推移它会慢的大部分时间。

ArrayLists work in a similar way but instead of rebuilding every time they double there capacity every time the limit is reached. so if you are constantly adding to it ArrayLists will be faster because recreating the array is fairly slow. So your implementation could use less memory if you are not adding to it often but as far as speed goes it will be slower most of the time.

这篇关于性能基本数组VS的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆