Array or List in Java. Which is faster?

后端 未结 30 1678
滥情空心
滥情空心 2020-11-22 04:30

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

30条回答
  •  太阳男子
    2020-11-22 05:01

    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 working version 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 without the optimization was clean, nice, and working.

提交回复
热议问题