Thursday, September 8, 2011

A fail case of optimization

I had a piece of code like this:

if (is_enemy(side, new_r, new_c)) {
    if (tolower(board[new_r][new_c]) == 'n') {
        return true;
    }
}

I optimized away the second if statement like this:

if (is_enemy(side, new_r, new_c)) {
    return tolower(board[new_r][new_c]) == 'n';
}

At the surface, this optimized version seems equivalent to the original version. Integrated into a bigger picture, this code fails terribly. Original code is like this:

for (int i = 0; i < 8; ++i) {
    if (is_enemy(side, new_r, new_c)) {
        if (tolower(board[new_r][new_c]) == 'n') {
            return true;
        }
    }
}

The optimized version forces a return maybe too early in the loop.

No comments:

Post a Comment