IF、CASE 和 WHILE 语句之间有什么区别
我只是想知道 Objective-C 中所有条件语句之间有什么区别,以及哪一个更快、更轻。
I just want to know what the difference between all the conditional statements in objective-c and which one is faster and lighter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
一条建议:不要再担心哪种语言结构在微观上比其他语言结构更快或更慢,而是关注哪些语言结构可以让你最好地表达自己。
One piece of advice: stop worrying about which language constructs are microscopically faster or slower than which others, and instead focus on which ones let you express yourself best.
If 和 case 语句描述了
While 语句 描述
由于这些语句执行不同的操作,因此争论哪个更快是没有意义的。
这就像问锤子是否比螺丝刀更快一样。
If and case statements described
While statement described
Since these statements do different things, it is unproductive to debate which is faster.
It's like asking whether a hammer is faster than a screwdriver.
与语言无关的版本(大多数情况下,显然这不适用于声明性语言或其他奇怪的语言):
当我学习编程时(很久以前,我会坦率地承认),一种语言由三种执行指令的方式组成:
if
和case
语句都是选择的变体。If
用于根据条件选择两个不同选项之一(使用伪代码):请记住,在这种情况下可能不需要
else
,它是有效的否则什么也不做
。另请记住,选项 1 或 2 也可能包含任何语句类型,包括更多if
语句(称为嵌套)。Case
略有不同 - 它通常意味着两个以上的选择,例如当您想要根据角色执行不同的操作时:请注意,您可以将
case
用于两个选项(甚至一个)但这有点像用热核弹头杀死一只苍蝇。While
不是一种选择变体,而是一种迭代变体。它属于for
、repeat
、until
以及许多其他可能性。至于哪个最快,在绝大多数情况下并不重要。编译器编写者比我们凡人更了解如何从他们的代码中获得最后一点性能。您要么相信他们能正确完成工作,要么您自己在汇编中手动编码(我更喜欢前者)。
通过专注于宏观而不是次要的事情,您将获得更高的性能。这包括选择适当的算法、分析和热点定位。找到每月需要五分钟的东西并在两分钟内运行它并没有什么好处。最好是在每分钟发生的事情上取得较小的改进。
像
if
、while
、case
等语言结构已经尽可能快了,因为它们被大量使用并且相对简单。您应该首先编写代码以提高可读性,并且仅在性能成为问题时才担心性能(请参阅 YAGNI)。即使您发现使用
if/goto
组合而不是case
可以让您运行得更快一些,但由此产生的源代码泥沼将更难维护。The language-agnostic version (mostly, obviously this doesn't count for declarative languages or other weird ones):
When I was taught programming (quite a while ago, I'll freely admit), a language consisted of three ways of executing instructions:
The
if
andcase
statements are both variants on selection.If
is used to select one of two different options based on a condition (using pseudo-code):keeping in mind that the
else
may not be needed in which case it's effectivelyelse do nothing
. Also remember that option 1 or 2 may also consist of any of the statement types, including moreif
statements (called nesting).Case
is slightly different - it's generally meant for more than two choices like when you want to do different things based on a character:Note that you can use
case
for two options (or even one) but it's a bit like killing a fly with a thermonuclear warhead.While
is not a selection variant but an iteration one. It belongs with the likes offor
,repeat
,until
and a host of other possibilities.As to which is fastest, it doesn't matter in the vast majority of cases. The compiler writers know far more than we mortal folk how to get the last bit of performance out of their code. You either trust them to do their job right or you hand-code it in assembly yourself (I'd prefer the former).
You'll get far more performance by concentrating on the macro view rather than the minor things. That includes selection of appropriate algorithms, profiling, and targeting of hot spots. It does little good to find something that take five minutes each month and get that running in two minutes. Better to get a smaller improvement in something happening every minute.
The language constructs like
if
,while
,case
and so on will already be as fast as they can be since they're used heavily and are relative simple. You should be first writing your code for readability and only worrying about performance when it becomes an issue (see YAGNI).Even if you found that using
if/goto
combinations instead ofcase
allowed you to run a bit faster, the resulting morass of source code would be harder to maintain down the track.while 不是条件,而是循环。区别在于 while 循环的主体可以执行多次,而条件循环的主体只能执行一次或根本不执行。
if 和 switch 之间的区别在于 if 接受任意表达式作为条件,而 switch 只接受值进行比较。基本上,如果你有一个类似
if(x==0) {} else if(x==1) {} else if(x==2) ...
的构造,它可以写很多使用 switch 更简洁(有效)。while isn't a conditional it is a loop. The difference being that the body of a while-loop can be executed many times, the body of a conditional will only be executed once or not at all.
The difference between if and switch is that if accepts an arbitrary expression as the condition and switch just takes values to compare against. Basically if you have a construct like
if(x==0) {} else if(x==1) {} else if(x==2) ...
, it can be written much more concisely (and effectively) by using switch.case 语句可以写为
But the case 效率更高,因为它只评估条件一次,然后分支。
while
仅当您希望多次评估某个条件并执行关联的代码块时才有用。如果您期望某个条件仅发生一次,那么它相当于if
。更恰当的比较是while
是更通用的for
。A case statement could be written as
But the case is much more efficient, since it only evaluates the conditional once and then branches.
while
is only useful if you want a condition to be evaluated, and the associated code block executed, multiple times. If you expect a condition to only occur once, then it's equivalent toif
. A more apt comparison is thatwhile
is a more generalizedfor
.每个条件语句都有不同的用途,您不会在每种情况下都使用相同的条件语句。了解哪些适合哪种情况,然后编写代码。如果您分析代码并发现存在瓶颈,那么您可以继续解决它。在真正出现问题之前,不要担心优化。
Each condition statement serves a different purpose and you won't use the same one in every situation. Learn which ones are appropriate for which situation and then write your code. If you profile your code and find there's a bottleneck, then you go ahead and address it. Don't worry about optimizing before there's actually a problem.
您是否在问 if 结构是否比大循环内的 switch 语句执行得更快?如果是这样,我进行了一个快速测试,将此代码放入我刚刚在最新的 Xcode 和 iPhone SDK 中创建的基于新视图的项目的 viewDidLoad 方法中:
此代码示例绝不完整,因为正如前面指出的,如果如果您有一种情况比其他情况出现的次数更多,您当然希望将其放在前面以减少比较的总数。它确实表明,在决策或多或少在分支之间平均分配的情况下,if 结构的执行速度会更快一些。
另外,请记住,这个小测试的结果在设备上运行与在模拟器中运行之间的性能差异很大。代码注释中引用的时间是在实际设备上运行的时间。 (显示的第一个时间是第一次运行代码时运行循环的时间,第二个数字是再次运行相同代码而无需重建的时间。)
Are you asking whether an if structure will execute faster than a switch statement inside of a large loop? If so, I put together a quick test, this code was put into the viewDidLoad method of a new view based project I just created in the latest Xcode and iPhone SDK:
This code sample is by no means complete, because as pointed out earlier if you have a situation that comes up more times than the others, you would of course want to put that one up front to reduce the total number of comparisons. It does show that the if structure would execute a bit faster in a situation where the decisions are more or less equally divided among the branches.
Also, keep in mind that the results of this little test varied widely in performance between running it on a device vs. running it in the emulator. The times cited in the code comments are running on an actual device. (The first time shown is the time to run the loop the first time the code was run, and the second number was the time when running the same code again without rebuilding.)
有条件语句和条件循环。 (如果维基百科是可信的,那么在编程中简单地提及“条件”并不涵盖条件循环。但这是一个小术语问题。)
Shmoopty 说,“由于这些语句做了不同的事情,所以争论哪个语句是没有意义的。更快。”
嗯……这可能是浪费时间,但这并不是无意义。例如,假设您有一个
if
语句:您可以将其转换为最多执行一次的循环:
后者在几乎任何语言中都会较慢(或相同的速度,因为优化器在幕后将其恢复为原始的
if
!)尽管如此,在计算机编程中有时(由于奇怪的情况)复杂的事情运行得更快但是这些事件很少而且相隔很远。重点应该放在你的代码上——什么让它最清晰,什么抓住了你的意图。
There are conditional statements and conditional loops. (If Wikipedia is to be trusted, then simply referring to "a conditional" in programming doesn't cover conditional loops. But this is a minor terminology issue.)
Shmoopty said "Since these statements do different things, it is nonsensical to debate which is faster."
Well... it may be time poorly spent, but it's not nonsensical. For instance, let's say you have an
if
statement:You can transform that into a loop that executes at most one time:
The latter will be slower in pretty much any language (or the same speed, because the optimizer turned it back into the original
if
behind the scenes!) Still, there are occasions in computer programming where (due to bizarre circumstances) the convoluted thing runs fasterBut those incidents are few and far between. The focus should be on your code--what makes it clearest, and what captures your intent.
循环和分支很难简单地解释,从任何 C 风格语言的构造中获得最佳代码取决于所使用的处理器和代码的本地上下文。主要目标是减少执行管道的中断——主要是通过减少分支错误预测。
我建议您转到此处满足您的所有优化需求。这些手册是为 C 风格程序员编写的,如果您了解一些汇编语言,那么相对容易理解。这些手册应该向您解释现代处理器的微妙之处、顶级编译器使用的策略以及构建代码以充分利用它的最佳方法。
loops and branches are hard to explain briefly, to get the best code out of a construct in any c-style language depends on the processor used and the local context of the code. The main objective is to reduce the breaking of the execution pipeline -- primarily by reducing branch mispredictions.
I suggest you go here for all your optimization needs. The manuals are written for the c-style programmer and relatively easy to understand if you know some assembly. These manuals should explain to you the subtleties in modern processors, the strategies used by top compilers, and the best way to structure code to get the most out of it.
我刚刚想起了关于条件和分支代码的最重要的事情。按如下顺序排列代码
您必须使用 else 序列...在这种情况下,CPU 中的预测逻辑将正确预测
x==1
并避免 80% 的管道中断全部执行。更多信息来自英特尔。特别:
通过遵循此规则,您可以直接向 CPU 提供提示,了解如何将其预测逻辑偏向链接条件。
I just remembered the most important thing about conditionals and branching code. Order your code as follows
You must use an else sequence... and in this case the prediction logic in your CPU will predict correctly for
x==1
and avoid the breaking of your pipeline for 80% of all execution.More information from intel. Particularly:
By following this rule you are flat-out giving the CPU hints about how to bias its prediction logic towards your chained conditionals.