我有一个while循环,我想只进行一次特定操作,并为所有其他循环运行执行不同的操作.
while (..) {
if ( 0 == count ) {
// do_this
} else {
// do_that
}
count++;
}
Run Code Online (Sandbox Code Playgroud)
在这里,count需要0仅与一次进行比较,但在每次循环运行中不必要地进行比较.有没有另一种方法,比较只发生一次,一旦成功不再被调用?
Art*_*Art 18
要么count == 0在循环之前做这件事,要么就是不可能(因为它正处于正在完成的其他事情的中间)只是编写你的代码是人类可读的,任何一半体面的编译器都会为你找到它.或者它不会弄明白,CPU中的分支预测器将完成这项工作.无论哪种方式,像这样的纳米优化很可能会花费你更多的时间来阅读代码,而不是节省执行时间.
{
// do_this
}
count = 1; /*assuming count previously started at zero*/
while (..) {
// do_that
count++; /*although some folk prefer ++count as it's never slower than count++*/
}
Run Code Online (Sandbox Code Playgroud)
更好