Java 中的数组或列表。哪个更快?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/716597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:41:26  来源:igfitidea点击:

Array or List in Java. Which is faster?

javaarrayslistperformance

提问by euphoria83

I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?

我必须在内存中保留数千个字符串才能在 Java 中连续访问。我应该将它们存储在数组中还是应该使用某种 List ?

Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ?

由于数组将所有数据保存在连续的内存块中(与列表不同),使用数组存储数千个字符串会导致问题吗?

采纳答案by Fortyrunner

I suggest that you use a profiler to test which is faster.

我建议您使用分析器来测试哪个更快。

My personal opinion is that you should use Lists.

我个人的意见是你应该使用列表。

I work on a large codebase and a previous group of developers used arrays everywhere. It made the code very inflexible. After changing large chunks of it to Lists we noticed no difference in speed.

我在一个大型代码库上工作,而以前的一组开发人员到处都使用数组。它使代码非常不灵活。在将它的大部分更改为 Lists 后,我们注意到速度没有差异。

回答by TofuBeer

If you know in advance how large the data is then an array will be faster.

如果您事先知道数据有多大,那么数组会更快。

A List is more flexible. You can use an ArrayList which is backed by an array.

List 更灵活。您可以使用由数组支持的 ArrayList。

回答by CookieOfFortune

No, because technically, the array only stores the reference to the strings. The strings themselves are allocated in a different location. For a thousand items, I would say a list would be better, it is slower, but it offers more flexibility and it's easier to use, especially if you are going to resize them.

不,因为从技术上讲,数组只存储对字符串的引用。字符串本身分配在不同的位置。对于一千个项目,我会说列表会更好,它更慢,但它提供了更大的灵活性并且更易于使用,尤其是当您要调整它们的大小时。

回答by Warrior

list is slower than arrays.If you need efficiency use arrays.If you need flexibility use list.

list 比arrays 慢。如果你需要效率使用arrays。如果你需要灵活性使用list。

回答by RV.

A List is more flexible.... so better to List than array

List 更灵活......所以 List 比数组更好

回答by cygil

The Java way is that you should consider what data abstractionmost suits your needs. Remember that in Java a List is an abstract, not a concrete data type. You should declare the strings as a List, and then initialize it using the ArrayList implementation.

Java 的方式是您应该考虑哪种数据抽象最适合您的需求。请记住,在 Java 中,列表是抽象的,而不是具体的数据类型。您应该将字符串声明为 List,然后使用 ArrayList 实现对其进行初始化。

List<String> strings = new ArrayList<String>();

This separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.

这种抽象数据类型和具体实现的分离是面向对象编程的关键方面之一。

An ArrayList implements the List Abstract Data Type using an array as its underlying implementation. Access speed is virtually identical to an array, with the additional advantages of being able to add and subtract elements to a List (although this is an O(n) operation with an ArrayList) and that if you decide to change the underlying implementation later on you can. For example, if you realize you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

ArrayList 使用数组作为其底层实现来实现列表抽象数据类型。访问速度几乎与数组相同,具有能够向 List 添加和减去元素的额外优势(尽管这是对 ArrayList 的 O(n) 操作),并且如果您稍后决定更改底层实现你可以。例如,如果您意识到需要同步访问,则可以将实现更改为 Vector,而无需重写所有代码。

In fact, the ArrayList was specifically designed to replace the low-level array construct in most contexts. If Java was being designed today, it's entirely possible that arrays would have been left out altogether in favor of the ArrayList construct.

事实上,ArrayList 专门设计用于在大多数情况下替换低级数组构造。如果 Java 是在今天设计的,那么完全有可能将数组完全排除在外而支持 ArrayList 构造。

Since arrays keep all the data in a contiguous chunk of memory (unlike Lists), would the use of an array to store thousands of strings cause problems ?

由于数组将所有数据保存在连续的内存块中(与列表不同),使用数组存储数千个字符串会导致问题吗?

In Java, all collections store only references to objects, not the objects themselves. Both arrays and ArrayList will store a few thousand references in a contiguous array, so they are essentially identical. You can consider that a contiguous block of a few thousand 32-bit references will always be readily available on modern hardware. This does not guarantee that you will not run out of memory altogether, of course, just that the contiguous block of memory requirement is not difficult to fufil.

在 Java 中,所有集合只存储对对象的引用,而不是对象本身。数组和 ArrayList 都将在一个连续数组中存储几千个引用,因此它们本质上是相同的。您可以认为,几千个 32 位引用的连续块在现代硬件上始终可用。这并不能保证您不会完全耗尽内存,当然,只是连续的内存块要求不难满足。

回答by JesperE

You should prefer generic types over arrays. As mentioned by others, arrays are inflexible and do not have the expressive power of generic types. (They do however support runtime typechecking, but that mixes badly with generic types.)

与数组相比,您应该更喜欢泛型类型。正如其他人所提到的,数组是不灵活的,并且没有泛型类型的表达能力。(然而,它们确实支持运行时类型检查,但这与泛型类型的混合很糟糕。)

But, as always, when optimizing you should always follow these steps:

但是,一如既往,在优化时,您应该始终遵循以下步骤:

  • Don't optimize until you have a nice, clean, and workingversion of your code. Changing to generic types could very well be motivated at this step already.
  • When you have a version that is nice and clean, decide if it is fast enough.
  • If it isn't fast enough, measure its performance. This step is important for two reasons. If you don't measure you won't (1) know the impact of any optimizations you make and (2) know where to optimize.
  • Optimize the hottest part of your code.
  • Measure again.This is just as important as measuring before. If the optimization didn't improve things, revert it. Remember, the code withoutthe optimization was clean, nice, and working.
  • 在您拥有一个漂亮、干净且可工作的代码版本之前,不要进行优化。在这一步很可能已经激发了更改为泛型类型的动机。
  • 当你有一个漂亮干净的版本时,决定它是否足够快。
  • 如果速度不够快,请测量其性能。这一步很重要,原因有二。如果您不进行测量,您将不会 (1) 知道您所做的任何优化的影响,以及 (2) 知道在哪里进行优化。
  • 优化代码中最热门的部分。
  • 再次测量。这与之前的测量一样重要。如果优化没有改善情况,则将其还原。请记住,没有优化的代码是干净、漂亮且有效的。

回答by potyl

Don't get into the trap of optimizing without proper benchmarking. As others have suggested use a profiler before making any assumption.

如果没有适当的基准测试,不要陷入优化的陷阱。正如其他人建议在做出任何假设之前使用分析器。

The different data structures that you have enumerated have different purposes. A list is very efficient at inserting elements in the beginning and at the end but suffers a lot when accessing random elements. An array has fixed storage but provides fast random access. Finally an ArrayList improves the interface to an array by allowing it to grow. Normally the data structure to be used should be dictated by how the data stored will be access or added.

您列举的不同数据结构有不同的用途。列表在开头和结尾插入元素非常有效,但在访问随机元素时会受到很大影响。阵列具有固定存储但提供快速随机访问。最后,ArrayList 通过允许数组增长来改进与数组的接口。通常,要使用的数据结构应由如何访问或添加存储的数据来决定。

About memory consumption. You seem to be mixing some things. An array will only give you a continuous chunk of memory for the type of data that you have. Don't forget that java has a fixed data types: boolean, char, int, long, float and Object (this include all objects, even an array is an Object). It means that if you declare an array of String strings [1000] or MyObject myObjects [1000] you only get a 1000 memory boxes big enough to store the location (references or pointers) of the objects. You don't get a 1000 memory boxes big enough to fit the size of the objects. Don't forget that your objects are first created with "new". This is when the memory allocation is done and later a reference (their memory address) is stored in the array. The object doesn't get copied into the array only it's reference.

关于内存消耗。你似乎混合了一些东西。数组只会为您拥有的数据类型提供连续的内存块。不要忘记 java 有固定的数据类型:boolean、char、int、long、float 和 Object(这包括所有对象,甚至数组也是 Object)。这意味着,如果您声明一个 String 字符串数组 [1000] 或 MyObject myObjects [1000],您只会得到 1000 个足够大的内存盒来存储对象的位置(引用或指针)。你不会得到 1000 个足够大的内存盒来容纳物体的大小。不要忘记您的对象首先是用“new”创建的。这是内存分配完成后,引用(它们的内存地址)存储在数组中的时间。对象不会被复制到数组中,只是它的引用。

回答by Apocalisp

"Thousands" is not a large number. A few thousand paragraph-length strings are on the order of a couple of megabytes in size. If all you want to do is access these serially, use an immutable singly-linked List.

“千”并不是一个很大的数字。几千个段落长度的字符串大小约为几兆字节。如果您只想串行访问这些,请使用不可变的单链 List

回答by PhiLho

I don't think it makes a real difference for Strings. What is contiguous in an array of strings is the references to the strings, the strings themselves are stored at random places in memory.

我认为这对字符串没有真正的影响。字符串数组中连续的是对字符串的引用,字符串本身存储在内存中的随机位置。

Arrays vs. Lists can make a difference for primitive types, not for objects. IFyou know in advance the number of elements, and don't need flexibility, an array of millions of integers or doubles will be more efficient in memory and marginally in speed than a list, because indeed they will be stored contiguously and accessed instantly. That's why Java still uses arrays of chars for strings, arrays of ints for image data, etc.

数组与列表可以对原始类型产生影响,而不是对对象。如果您事先知道元素的数量,并且不需要灵活性,那么与列表相比,数百万个整数或双精度数的数组在内存中的效率更高,速度也略有提高,因为它们确实会连续存储并立即访问。这就是为什么 Java 仍然使用字符数组作为字符串,使用整数数组作为图像数据等。