Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array or List in Java. Which is faster?

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 ?

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 ?

like image 690
euphoria83 Avatar asked Apr 04 '09 05:04

euphoria83


People also ask

Which is faster array or list?

An Array is a collection of similar items. Whereas ArrayList can hold item of different types. An array is faster and that is because ArrayList uses a fixed amount of array.

Is list better than array in Java?

Array is a fixed length data structure whereas ArrayList is a variable length Collection class. We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java.

Which is fast array or ArrayList?

Arrays are better in performance. ArrayList provides additional functionality such as "remove" at the cost of performance. because it's backed by an underlying array. therefore, anything wrapping an array cannot be faster than the array.

Are lists slower than arrays?

Since List<> uses arrays internally, the basic performance should be the same. Two reasons, why the List might be slightly slower: To look up a element in the list, a method of List is called, which does the look up in the underlying array. So you need an additional method call there.


1 Answers

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.

like image 171
Fortyrunner Avatar answered Sep 27 '22 20:09

Fortyrunner