【发布时间】:2013-10-03 05:59:18
【问题描述】:
我一直在研究一些优化 LinkedList 的方法。有谁知道 Java 默认的双向链接 LinkedList 类是否经过优化以反向执行 get() 操作?
例如:
// Some LinkedList list that exists with n elements;
int half = list.size() / 2;
list.get(half + 1);
调用list.get(half + 1) 是否会优化搜索并反向进行,因为它是一个双向链表?如果您知道该元素位于列表的后半部分,那么从末尾进行搜索并朝着中心进行搜索会更有意义。
我知道使用 get(index) 是 O(n) 时间,并且您应该在遍历 LinkedList 时使用迭代器,但我只是好奇。
【问题讨论】:
-
就在 javadocs 的第三段(Java 7 中的第二段):
Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index. -
请注意,从性能POV来看,LinkedList的大多数使用无论如何都是错误的。
标签: java performance data-structures linked-list