4

While solving a mindless task, a question came to my mind:

/**
* 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;
}

In the while block, only one if statement can be true. So the while block could be written using continue instead of else if:

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();
}

Is there any difference in performance between the two methods?

Affe
  • 53
  • 1
  • 1
  • 7

2 Answers2

3

If you are covering all cases you can omit last condition and write simply:

else { //found element
    return node.getElement();
}

And in your second example you can change:

if (node.getKey().compareTo(key) == 0) { //found element
    return node.getElement();
}

to simply:

return node.getElement();

Your two examples are equivalent but first one is easier to read. It is easier to spot that every case is covered when you have:

if ..
else if ..
else ..

then when we have only if blocks.

rtruszk
  • 3,902
  • 13
  • 36
  • 53
2

No difference. The compiler should generate exactly the same bytecode in this case. Hence no performance difference could exist.

M A
  • 71,713
  • 13
  • 134
  • 174