Asked  7 Months ago    Answers:  5   Viewed   34 times

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 ?

 Answers

21

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.

Tuesday, June 1, 2021
 
ammezie
answered 7 Months ago
94

How about this?

Integer[] ints = new Integer[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);
Tuesday, June 1, 2021
 
dimitarvp
answered 7 Months ago
96

Java 9 brings similar methods: List#of, Set#of, Map#of with several overloaded methods to avoid calling the varargs one. In case of Map, for varargs, you have to use Map#ofEntries.

Pre Java 9, you had to use Arrays#asList as entry point to initialize List and Set:

List<String> list = Arrays.asList("hello", "world");
Set<String> set = new HashSet<>(Arrays.asList("hello", "world")); 

And if you wanted your Set to be immutable, you had to wrap it inside an immutable set from Collections#unmodifiableSet:

Set<String> set = Collections.unmodifiableSet(
    new HashSet<>(Arrays.asList("hello", "world")));

For Map, you may use a trick creating an anonymous class that extended a Map implementation, and then wrap it inside Collections#unmodifiableMap. Example:

Map<String, String> map = Collections.unmodifiableMap(
    //since it's an anonymous class, it cannot infer the
    //types from the content
    new HashMap<String, String>() {{
        put.("hello", "world");
    }})
    );
Monday, August 23, 2021
 
OneNoOne
answered 4 Months ago
49

JIT will change (optimize) your code on runtime, so this is not important in Java. One simple JIT optimization is method inlining.

For further optimization read about Micro Benchmarking and look at this question How do I write a correct micro-benchmark in Java?

Monday, October 4, 2021
 
Daveel
answered 2 Months ago
56

They're both fast enough to be over before you know it. Better to go for the one that you can read more easily.

But from forums, blogs contains is faster, but still negligible performance difference

Wednesday, November 3, 2021
 
Anass Kartit
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share