性能原始数组与 ArrayList [英] Performance primitive Array vs ArrayList

查看:29
本文介绍了性能原始数组与 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?

推荐答案

ArrayLists 以类似的方式工作,但不是每次达到限制时每次将容量加倍时重建.因此,如果您不断向它添加 ArrayLists 会更快,因为重新创建数组相当慢.因此,如果您不经常添加内存,您的实现可能会使用更少的内存,但就速度而言,大多数情况下它会更慢.

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.

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

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