在解决一项机械任务时,我想到了一个问题:
/**
* Find element by key in binary tree.
*/
public E find(K key) {
BinaryTreeNode<K, E> node = this.root;
while (node != null) {
if (node.getKey().compareTo(key) > 0) { //element in tree too big
node = node.getLeft();
} else if (node.getKey().compareTo(key) < 0) { //element in tree too small
node = node.getRight();
} else { //found element
return node.getElement();
}
}
return null;
}
在
while
块中,只有一个if
语句可以为真。因此,可以使用continue
来代替else if
编写while
块:while (node != null) {
if (node.getKey().compareTo(key) > 0) { //element in tree too big
node = node.getLeft();
continue;
}
if (node.getKey().compareTo(key) < 0) { //element in tree too small
node = node.getRight();
continue;
}
//found element
return node.getElement();
}
这两种方法的性能有什么区别吗?