简体   繁体   中英

Is it optimal to check a variable before setting it?

Is if(foo) bar |= foo; more optimal than just bar |= foo; ?

Is reading data stored in a variable somehow faster than writing it (ignoring hardware-specific limitations) so it is actually worth to check it before performing some operation?

In theory:

It depends what processor you are running (how fast a compare is vs how vast bit operations are). It also depends how often foo will be 0. If never then you gain nothing (and actually slow it down)

In reality:

Unless you need to do this 100 million times on stressed out hardware (think realtime embedded) it makes no difference.

Is if(foo) bar |= foo; more optimal than just bar |= foo; ?

No, it's most likely far worse. The if you add creates a branch in your compiled program which degrades performance compared to the single branchless instruction.

In if(foo) bar |= foo; you are at best doing only 1 or 2 instructions (depending on the architecture): comparison and branching. At worst 2 or 3 instructions (again depending on the architecture): comparison, branching and bitwise OR. Instead, in bar |= foo you are always doing one instruction only. Of course, the compiler can optimize the code to some extent, but using the if here is nonetheless basically useless. And of course, the cost of a compare instruction could be less than the cost of a bitwise OR in some architecture, but the combination of comparison and conditional branching is almost certainly going to be more than the cost of a single bitwise OR.

Is reading data somehow faster than writing (ignoring hardware-specific conditions) so it is actually worth to check it before performing some specific operation on that variable?

The problem is not really reading or writing data (which will most likely be in a CPU register anyway for that single operation), but performing 2/3 instructions instead of 1, while also branching. Branching further degrades performance because in modern CPUs which use branch predictors it can (to make it simple) cause the CPU cache to be flushed away, therefore needing to re-read the code a second time. See Why is processing a sorted array faster than processing an unsorted array?

Doing something like if (cond) { statements; } if (cond) { statements; } is only useful if the cost of evaluating cond plus branching is significantly less than the cost of the statements; executed conditionally. For a single simple mathematical instruction, this is almost never the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM