我建议您使用探查器来测试哪个更快。
我个人认为您应该使用列表。
我在大型代码库上工作,以前的一组开发人员到处使用数组。它使代码非常不灵活。将其大块更改为“列表”后,我们注意到速度没有差异。
我写了一个基准测试来比较ArrayLists和Arrays。在我的老式笔记本电脑上,遍历5000个元素的数组列表的时间为1000次,比同等的数组代码慢大约10毫秒。
所以,如果你在做什么,但迭代的列表,你做了很多,那么也许它的价值的最优化。否则,我会使用列表中,因为它会更容易,当你这样做需要优化的代码。
我确实注意到使用for String s: stringsList
它比使用老式的for循环访问列表要慢50%。走吧,这是我计时的两个功能。数组和列表中填充了5000个随机(不同)字符串。
private static void readArray(String[] strings) {
long totalchars = 0;
for (int j = 0; j < ITERATIONS; j++) {
totalchars = 0;
for (int i = 0; i < strings.length; i++) {
totalchars += strings[i].length();
}
}
}
private static void readArrayList(List<String> stringsList) {
long totalchars = 0;
for (int j = 0; j < ITERATIONS; j++) {
totalchars = 0;
for (int i = 0; i < stringsList.size(); i++) {
totalchars += stringsList.get(i).length();
}
}
}