Optimization

I

InuY4sha

How much can I save from this
if (! (*ptr & MY_CONST) ){}
and this
if (*ptr != MY_CONST){}
thanks, cheers
 
V

vippstar

How much can I save from this
if (! (*ptr & MY_CONST) ){}
and this
if (*ptr != MY_CONST){}
thanks, cheers

#define MYCONST 3
*ptr = 1;

Under these conditions the behavior will not be the same.
 
S

swengineer001

How much can I save from this
       if (! (*ptr & MY_CONST) ){}
and this
       if (*ptr != MY_CONST){}
thanks, cheers

Shouldn't that be an exclusive or operator in the first one to give
you the same logical result.
 
B

Ben Pfaff

InuY4sha said:
How much can I save from this
if (! (*ptr & MY_CONST) ){}
and this
if (*ptr != MY_CONST){}

You could omit the whole thing, since it has no side effects
(unless ptr or *ptr is qualified with volatile). That would save
you a line of code.
 
J

John Bode

How much can I save from this
if (! (*ptr & MY_CONST) ){}
and this
if (*ptr != MY_CONST){}
thanks, cheers

You won't save anything, because the two forms will give you different
answers for the same inputs. If *ptr and MY_CONST share *any* bits in
common, the first form will evaluate to 0, which is not the same as
the second form.

It doesn't matter how fast your code is if it gives you the wrong
answer. This kind of premature micro-optimization leads to code that
is often buggy and difficult to maintain. You should only resort to
this kind of trickery if a) you are failing to meet a hard performance
requirement, b) profiling of the code reveals that this particular
expression really is the bottleneck, c) the proposed change really
buys you the performance you need, and d) the result of the optimized
expression is the same as the unoptimized expression.

For this situation, it's unlikely you'd see any appreciable difference
in performance, but the only way to know for sure is to code up both
versions, profile them, and compare the results. But again, the
"optimized" version gives different results from the "unoptimized"
version.
 
A

Andrey Tarasevich

InuY4sha said:
How much can I save from this
if (! (*ptr & MY_CONST) ){}
and this
if (*ptr != MY_CONST){}

Your question, as stated, doesn't make any sense, since the two
expressions are not equivalent.

Anyway, replacing simple expression with another equivalent expression
won't normally have any optimizing effect, because any half-decent
compiler normally knows by itself the most optimal way (of many
equivalent ways) to implement the operation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top