java的链表比增加元素时,ArrayList的慢? [英] java linkedlist slower than arraylist when adding elements?

查看:152
本文介绍了java的链表比增加元素时,ArrayList的慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想linkedlists被认为添加元素时会比一个ArrayList快?我只是做它需要多长时间才能添加,排序和搜索元素(ArrayList的VS链表VS HashSet的)测试。我只是使用ArrayList和LinkedList的java.util中的类......同时使用的添加(对象)方法提供给每个类。

i thought linkedlists were supposed to be faster than an arraylist when adding elements? i just did a test of how long it takes to add, sort, and search for elements (arraylist vs linkedlist vs hashset). i was just using the java.util classes for arraylist and linkedlist...using both of the add(object) methods available to each class.

ArrayList的表现出在LinkedList的填充列表...和线性搜索列表。

arraylist out performed linkedlist in filling the list...and in a linear search of the list.

这是正确的?我没有做错事的实施可能?

is this right? did i do something wrong in the implementation maybe?

***************EDIT*****************

***************EDIT*****************

我只是想确保我用这些东西吧。下面是我在做什么:

i just want to make sure i'm using these things right. here's what i'm doing:

public class LinkedListTest {

    private List<String> Names;

    public LinkedListTest(){
            Names = new LinkedList<String>();
    }

然后,我只是用LinkedList的方法,即Names.add(串)。而当我测试的ArrayList,这是几乎相同的:

Then I just using linkedlist methods ie "Names.add(strings)". And when I tested arraylists, it's nearly identical:

public class ArrayListTest {

    private List<String> Names;

    public ArrayListTest(){
            Names = new ArrayList<String>();
    }

我这样做对吗?

推荐答案

是的,这是正确的。 的LinkedList 将不得不这样做的每个插入内存分配,而的ArrayList 被允许做他们的少了,给它摊销O(1)插入。存储器分配看起来便宜,但也可以是实际上是非常昂贵的。

Yes, that's right. LinkedList will have to do a memory allocation on each insertion, while ArrayList is permitted to do fewer of them, giving it amortized O(1) insertion. Memory allocation looks cheap, but may be actually be very expensive.

线性搜索时间可能较慢的LinkedList 由于局部性:在的ArrayList 元素紧密联系起来,所以有较少的缓存未命中

The linear search time is likely slower in LinkedList due to locality of reference: the ArrayList elements are closer together, so there are fewer cache misses.

当你打算只在列表 ArrayList的末尾插入是首选的实现。

When you plan to insert only at the end of a List, ArrayList is the implementation of choice.

这篇关于java的链表比增加元素时,ArrayList的慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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