简体   繁体   English

递归 - 干净的代码与性能

[英]Recursion - clean code vs performance

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.假设我正在扫描一个 NxN 数组,使用 JAVA 中的递归,我唯一的停止条件是留在数组边界。

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).据我所知,这可以节省 4N 次递归调用(4N 次新堆栈帧)。

So, would it be 'more correct' to write the second function in order to avoid unnecessary calls?那么,编写第二个函数以避免不必要的调用是否“更正确”?

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.由于脏代码而引入的一个错误在纯美元方面可能比与稍微脏的代码相关的服务器成本高得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM