问题是,“我们可能期望method3运行得比method2快,为什么会这样?”但我不知道。看起来这两种方法都可以执行相同的操作。有人请赐教吗?for循环性能迭代
ArrayList<Person> method2(Person x, ArrayList<Person> people){
ArrayList<Person> friends = new ArrayList<Person>();
for (Person y : people) if (x.knows(y)) friends.add(y);
return friends;
}
ArrayList<Person> method3(Person x, ArrayList<Person> people){
ArrayList<Person> friends = new ArrayList<Person>();
for (int=0; i<people.size(); i++){
Person y = people.get(i);
if (x.knows(y)) friends.add(y);
}
return friends;
}
在现实世界中,99.99%的时间,这两种方法之间唯一有意义的区别是可读性。 2之间的性能差异取决于列表的大小,以及ArrayList如何实现get和getItorator方法,并且几乎不会影响;任何基于类实现的设计选择总是本质上是错误的(除非你需要挤出每一分性能,在这种情况下,你很可能会在较低的水平上编码) – Tezra