Which of the following is faster?

for (int i = 0; i < n; ++i)

or

for (int i = 0; i != n; ++i)

I'm wondering because I don't understand hardware and thus don't understand how a computer looks at < versus !=.

有帮助吗?

解决方案

For primitive types, both operations take the exact same amount of time since both are actually determined regardless of which you ask for.

In short, whenever you make a basic comparison, < <= > >= == or !=, one side of the operator is subtracted from the other. The result of the subtraction is then used to set a number of flags, the most important of which are Z (zero), N (negative), and O (overflow). Based on the names, you should be able to figure out what each flag represents. Ex: if the result of subtraction is zero, than the Z flag is set. Thus, whether you ask for <= or !=, all the processor is doing is checking the flags which have all been set appropriately as a result of the initial subtraction.

Theoretically, <= should take slightly longer since two flags (Z and N) must be checked instead of one (= just cares about Z). But this happens on such a low level that the results are most likely negligible even on a microsecond scale.

If you're really interested, read up on processor status registers.

For non-primitive types, i.e. classes, it depends on the implementation of the relational operators.

其他提示

These compile to exactly the same number of machine instructions - both Jump on Equality and Jump if Less are single Assembly instructions. You can read about these instructions here: http://en.wikibooks.org/wiki/X86_Assembly/Control_Flow#Jump_on_Equality

The comparisons < and != both take a single instruction, however the values of the two operands need to be loaded into the registers first.

For primitive data types such as int, bool, etc, each comparison will take 3 CPU instructions. For other data types it will take at least 3 instructions but maybe more.

It can also depend on the compiler and the compile-time optimisations used.

If you change the value of i in the loop body to something greater than n (perhaps you need to increment i twice if a specific condition is met, and this could happen on the last iteration), or change n to something less than i, then the second version (with !=) the loop will not terminate.

If you want to iterate n times, then the first version (with <) is a bit safer.

It's easier to prove the first version will terminate.

(though unlikely, if you literally want the loop to continue iterating if n == i is skipped, then use the second version obviously)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top