Reputation: 47
I have a small conflict between writing a clean code vs. performance overhead.
Assuming I'm scanning a NxN array, using a recursion in JAVA, and my only stopping condition is stay in the array boundary.
I can write the function as follow, which is more clean and readable:
private void move(int x, int y){
if(outOfBound(x,y)){ \\ stopping condition
return;
}
move(x+1, y);
move(x, y+1);
move(x-1, y);
move(x, y-1);
}
Or I can write it as follow:
private void move(int x, int y){
if(!outOfBound(x+1,y)){ \\ stopping condition
move(x+1, y);
}
if(!outOfBound(x,y+1)){ \\ stopping condition
move(x, y+1);
}
if(!outOfBound(x-1,y)){ \\ stopping condition
move(x-1, y);
}
if(!outOfBound(x,y-1)){ \\ stopping condition
move(x, y-1);
}
}
Which, as far as I know, can save 4N recursive calls (4N new stack frames).
So, would it be 'more correct' to write the second function in order to avoid unnecessary calls?
Upvotes: 1
Views: 609
Reputation: 6641
There is only one way to solve this dilemma - measure the performance in actual project context.
If this is seriously affecting performance in real life scenarios, and becoming a bottleneck, by all means change it to the less optimal one.
On the other hand, if it is not really making a difference in overall performance of your app, let it be cleaner. One bug introduced because of dirty code can cost you much more in pure dollar terms than the server costs associated to the code being slightly dirtier.
Upvotes: 1