关于 XCode 的 If-Else 语句的问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5775220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:54:07  来源:igfitidea点击:

Question on If-Else statements on XCode

objective-cxcodeiosxcode4

提问by IBG

Is using this code:

正在使用此代码:


if (foobar == 1)    
{  
 method(a)  
}   
else if (foobar == 2)      
{   
 method(b)   
}

void method (foo)   
{   
//method 1foo   
//method 2foo   
//method 3foo   
}

makes it more faster, or compile to a smaller executable, than this code:

使它比此代码更快,或编译为更小的可执行文件:


if (foobar == 1)    
{   
//method 1a   
//method 2a   
//method 3a   
}   
else if (foobar == 2)   
{   
//method 1b   
//method 2b   
//method 3b   
}   

or has any effect at all when compiled on Xcode?

或者在 Xcode 上编译时有什么影响?

I know the codes are sketchy. Sorry. Thanks for the tip on the edit, Mr. Dave.

我知道代码很粗略。对不起。感谢您对编辑的提示,戴夫先生。

回答by Caleb

Don't Repeat Yourself. Yes, you can avoid the tiny overhead of a function call by eliminating the function and copying its contents everywhere you use it, but that's not a good way to speed up your program. The difference in speed will be so small that you probably won't be able to detect it even after many, many iterations. And you're just begging for bugs where you change one spot but not the other(s).

不要重复自己。是的,您可以通过消除函数并在使用它的任何地方复制其内容来避免函数调用的微小开销,但这不是加速程序的好方法。速度差异非常小,即使经过多次迭代,您也可能无法检测到它。你只是在乞求你改变一个地方而不是其他地方的错误。

回答by Chazbot

Assuming that the main difference you're asking about is in the use of the external method outside your conditional statement...

假设您要问的主要区别在于在条件语句之外使用外部方法...

No, not that I can think of. However, in any language it's usually a good idea to encapsulate common functionality in a single method wherever possible, to keep things organized and easy to read. In other words, I'd go with your first option. =)

不,不是我能想到的。然而,在任何语言中,尽可能将通用功能封装在单个方法中通常是一个好主意,以保持组织有序并易于阅读。换句话说,我会选择你的第一个选项。=)

回答by Tom Dalling

What you've described is known as inlining. Inlining generally makes the code faster, but it can make the code slower in certain cases. In any case, unless the rest of the code is already highly optimised and it's in a very tight loop, you won't notice any speed difference.

您所描述的内容称为内联。内联通常会使代码更快,但在某些情况下它会使代码变慢。在任何情况下,除非其余代码已经高度优化并且处于非常紧凑的循环中,否则您不会注意到任何速度差异。