除非“直到"循环会更有效吗? [英] Wouldn't a "do until" loop be more efficient?

查看:64
本文介绍了除非“直到"循环会更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,我注意到一种重复出现的模式是必须经常使用while循环(例如while (!isEmpty())

I am new to programming, and one reoccuring pattern I notice is the frequent negation I have to use with while loops, for example while (!isEmpty())

如果有一个直到"循环,例如在条件成立之前做些什么?我确实知道取反发生在寄存器上并且非常快,但是看起来还是可以避免的.

Wouldn't it be better performance wise if there was a "until" loop, e.g. do something until a condition is true? I do realize negation happens on registers and is very fast, but still it looks like it can be avoided.

也许汇编语言有些东西使它最好使用当前建立的方法,即使它经常需要取反?

Or maybe there is something about assembly language that makes it preferable to use the currently established approach, even if it frequently requires negation?

推荐答案

否定很可能不会以任何时间明确地发生.

The negation most likely won't happen explicitly in a way that takes any time.

首先,天真的"while"实现在x86上看起来像这样

First off, the naive "while" implementation looks like this on x86

_loophead:
  call _isEmpty
  test eax, eax ; return value is in eax
  jnz _loopend  ; break out of loop if condition is not zero
  ... ; loop body here
  jmp _loophead
_loopend:

那里没有实际的否定,只是一个jnz,如果不为零,则跳".什么不为零?影响标志"的最后一件事-它上方的测试,用于测试isEmpty()的返回值.

There is no actual negation there, just a jnz that "jumps if not zero". What is not zero? The last thing that affected "the flags" - the test above it that tests the return value of isEmpty().

更好的同时"实现(因为每次迭代仅需要1个分支)看起来像

A better "while" implementation (because it takes only 1 branch per iteration) looks like

  jmp _looptest
_loopstart:
  ... ; loop body
_looptest:
  call _isEmpty
  test eax, eax
  jz _loopstart  ; continue loop if condition is zero

否定(如果存在)不花费额外的时间/指令/空间.在许多其他处理器上也是如此.

The negation, when it exists, takes no additional time/instructions/space. This is also the case on many other processors.

此外,如果可以内联_isEmpty,则该条件很可能甚至根本不在寄存器中,它将成为标志状态的一部分(特殊情况下为单个登记). 布尔值是0或1的整数"之类的内容是概念语义的一部分,通常在实际实现中进行了优化.通常,您不需要那个0/1值-大多数情况下,您要做的第一件事就是再次将其放回标志寄存器中,以便您可以在其上进行分支.

Furthermore, if _isEmpty can be inlined, the condition most likely won't even really be in a register, it'll be part of the flags state (a single bit in a special register). Things such as "a boolean is an integer that is 0 or 1" are part of the conceptual semantics and are often optimized out in real implementations. You usually don't need that 0/1 value - most of the time the first thing you'll do with it is put it back in the flags register again so you can branch on it.

即使是非常早的C编译器,也要花很多精力将用作条件的布尔"编译为比从中生成0/1整数更有效的代码.

Even very early C compilers took special effort to compile a "bool used as condition" to more efficient code than making a 0/1 integer out of it.

这篇关于除非“直到"循环会更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆