Is it worth using binary operators to gain performance?

6

I have the following situations:

if (1 & 1){}

and

if (1 == 1){}

According to what I've learned, working with bitwise operators causes a much better performance in the program, so I've had some doubts:

  • Is performance in the first situation really better than in the second? Why?

  • Is there a situation where using a binary operator will cause a worse performance?

asked by anonymous 03.01.2018 / 22:04

1 answer

6

In many cases yes, many do not. In general the recommendation is not to use them until the performance is not good enough or that only the manipulation is adequate for the desired semantics, because current compilers often change the arithmetic or relational operation by bit manipulation whenever advantageous. But it does not solve every case in the best way. Most solves better than the programmer.

In such artificial examples, the code will actually be reduced to nothing . Only the header and footer of the function (in some cases even this):

Justtestingonthespecificsituationinthespecificimplementation,onthespecificarchitecture,toseeifitgetsfasterornot.

It'susefultodothiswhenyouneedperformanceandknowthatthecompilerisnotoptimizingproperly.

Itisalsousefulifthesemanticsareoflower-levelnumbermanipulation,astheintentistoactuallytinkerwithbitsratherthanahigh-levelnumber.

Insomecasestheprocessorcanoptimizeexecution,evenbeyondthisoperation,dependingontheinstructionusedinthecode,butonlythecompilerknowswhatinstructionitused.

Soitalsogoesalittletasteinmostcases.

Ifyouuseitwrongeverythingcanbeworse.

Ididnotevenmentionthedifferencebetweenprocessors.Andit'snotjustfamily,itvariesbymodel.

Soitdepends,youcannotanswersomethingthatdoesnotevenhaveadefinitiveanswer.

The fact of generating different codes does not mean that one is faster than the other since each instruction has a different execution time and depends on the general context and the execution environment. It is possible to measure, but it gives work. The compiler version and settings can change the generated code.

    
03.01.2018 / 22:33