[英]How to increase performance of a doubly linked list in java?
因此,我有一项作业,要求我修改遍历双向链表的方法。 我上班了,但是我们教授。 设置它的方式是,如果这些方法比他提供的方法运行得更快,则您只能获得满分。 该列表是10000个元素。
这是原始文件遍历列表的方式:
private Node getNodeAt(int givenPosition)
{
Node currentNode = firstNode;
for(int counter = 1; counter < givenPosition; counter++)
{
currentNode = currentNode.next;
}
return currentNode;
这大约需要1331毫秒。 这是我们被告知遍历列表的一种方法:
private Node getNodeAt2(int givenPosition)
{
Node currentNode = firstNode;
middleNode = firstNode;
boolean nearFront = givenPosition <= (numberOfEntries / 4);
boolean nearFrontMid = (givenPosition < (numberOfEntries / 2)) && (givenPosition > (numberOfEntries / 4));
boolean nearBackMid = (givenPosition >= (numberOfEntries / 2)) && (givenPosition < ((3*numberOfEntries) / 4));
boolean nearLast = (givenPosition >= ((3*numberOfEntries) / 4));
middlePosition = numberOfEntries / 2;
for(int counter = 1; counter < middlePosition; counter++)
{
middleNode = middleNode.next;
}
if(nearFront){
currentNode = firstNode;
for(int counter = 1; counter < givenPosition; counter++)
{
currentNode = currentNode.next;
}
}
if(nearFrontMid){
currentNode = middleNode;
for(int counter = 1; counter <= (middlePosition - givenPosition) ; counter++)
{
currentNode = currentNode.previous;
}
}
if(nearBackMid){
currentNode = middleNode;
for(int counter = 1; counter <= (givenPosition - middlePosition); counter++)
{
currentNode = currentNode.next;
}
}
if (nearLast){
currentNode = lastNode;
for(int counter = 1; counter <= (numberOfEntries - givenPosition); counter++)
{
currentNode = currentNode.previous;
}
}
return currentNode;
这个过程大约需要800毫秒,尽管速度更快,但他预计这将花费第一种方法花费的时间的四分之一。 那可能吗?
一些想法:
1)在第二个解决方案中,总是搜索middleNode,但并非每次都需要搜索(尤其是在if-parts nearfront和nearlast)。 如果仅在需要时确定MiddleNode,它将更快。
2)迭代速度更快,因为该方法知道中间节点在哪里。 也许“ quaterNodes”的帮助。
3)有时循环迭代比循环快。 无需循环调用距离所需位置更近1步的方法。 具有10000个元素将没有任何限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.