Question on If-Else statements on XCode
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?
I know the codes are sketchy. Sorr开发者_JAVA技巧y. Thanks for the tip on the edit, Mr. Dave.
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).
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. =)
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.
精彩评论