473,320 Members | 2,041 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

which is faster ?

which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}

Nov 14 '05 #1
18 1623
if (x!=0) if your cpu is x86, otherwise i don't know.

if you choose optimise, i don't know either

Nov 14 '05 #2
junky_fel...@yahoo.co.in wrote:
which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}


It depends on your platform, the Standard has nothing to say about
this. Why don't you test it yourself on your machine?

You should also note that the above tests are not equivalent. If x is
2 then the first test will be false while the second will be true. You
should be more worried about writing clear code that makes sense in
your situation and let the compiler worry about how to best perform the
test for you since it undoubtedly knows more than you do about how best
to optimize such an expression.

Rob Gamble

Nov 14 '05 #3
On 16 May 2005 04:57:30 -0700, ju**********@yahoo.co.in wrote:
which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}


First answer the question of which gives you the right answer.

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #4
ju**********@yahoo.co.in wrote:
which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}


In practice it would probably be

if (x) { ... }
-- August
Nov 14 '05 #5
August Karlstrom <fu********@comhem.se> writes:
ju**********@yahoo.co.in wrote:
which of the following is faster and why ?
if ( x == 1 ) {
}
or
if ( x != 0 ) {
}


In practice it would probably be

if (x) { ... }


Not likely. "if (x)" is precisely equivalent to "if (x != 0 )".
There's no reason to expect that either will be faster than the other.
For any reasonable compiler, both will result in exactly the same
generated code.

On the other hand, comparing the speed of "x != 0" vs. "x == 1" is
unlikely to be useful, since they aren't semantically equivalent
(unless you can prove that the value of x is either 0 or 1).

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
Keith Thompson <ks***@mib.org> writes:
On the other hand, comparing the speed of "x != 0" vs. "x == 1" is
unlikely to be useful, since they aren't semantically equivalent
(unless you can prove that the value of x is either 0 or 1).


But that's a very common situation in C, because all of the
relational, equality, and logical operators yield either 0 or 1.
--
Go not to Usenet for counsel, for they will say both no and yes.
Nov 14 '05 #7
ju**********@yahoo.co.in wrote:
which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}

The two comparisons are different.
In the first, you are comparing to an exact value,
the other you are checking for not zero.

Many processors have an instruction that allows
branching if a value is not zero, and also if
the value is zero. So, in some processors, the
second comparison can be reduced to a single
jump instruction.

In some processors, the first comparison requires
issuing a compare instruction to set the condition
codes, then a branch on that condition. Thus,
two instructions are required. If the values are
already in registers, some processors can execute
the first comparison with one instruction.

As to which is faster, neither. They break the
sequential flow of instructions. This break may
take up more time than the execution of the
instructions. For more efficient programs, try
implementing Boolean Arithmetic instead of using
compares. The objective is to reduce the breaks
in the sequential execution of instructions.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library
Nov 14 '05 #8
Keith Thompson wrote:
.... snip ...
Not likely. "if (x)" is precisely equivalent to "if (x != 0 )".
There's no reason to expect that either will be faster than the
other. For any reasonable compiler, both will result in exactly
the same generated code.


That depends on the optimization. There is no reason to prefer:

load x
cpi 0
jz ...

versus

test x
jz ...

where, for a suitable machine, the sequences will be generated by
slavishly following the C source. Being anachronistic, I prefer
having the control via the optimization level. Besides, a compiler
that is sufficiently slavish is probably much smaller and faster.

--
Some informative links:
news:news.announce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
Nov 14 '05 #9
In article <11**********************@g14g2000cwa.googlegroups .com>,
ju**********@yahoo.co.in wrote:
which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}


A pointless question, since they don't do the same thing.

The rule of thumb for speed is:

1. If it doesn't work then speed doesn't matter.

2. If nobody pays money to make it faster then speed doesn't matter.

3. If it works, and if people complain that it is too slow, then it is
time to learn to use a profiler. If you haven't profiled it, then trying
to make it faster is a waste of time.

4. If you have to ask whether x==1 or x!=0 is faster, then you can be
sure that the answer will not solve any speed problems you might have.
Nov 14 '05 #10
In article <ch*********************************@slb-newsm1.svr.pol.co.uk>,
Christian Bau <ch***********@cbau.freeserve.co.uk> wrote:
The rule of thumb for speed is: 1. If it doesn't work then speed doesn't matter.


Well, that explains MS Windows then ;-)
--
Warning: potentially contains traces of nuts.
Nov 14 '05 #11
Christian Bau wrote:
In article <11**********************@g14g2000cwa.googlegroups .com>,
ju**********@yahoo.co.in wrote:

which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}

A pointless question, since they don't do the same thing.


Note that the OP doesn't state that they do the same thing.

-- August
Nov 14 '05 #12
In article <7U***************@newssvr17.news.prodigy.com>,
Thomas Matthews <Th*************************@sbcglobal.net> wrote:
ju**********@yahoo.co.in wrote:
if ( x == 1 ) {
if ( x != 0 ) {
As to which is faster, neither. They break the
sequential flow of instructions. This break may
take up more time than the execution of the
instructions.


It gets worse than that -- it can depend on what's in the { }
afterwards. If the statements afterwards consist of relatively
simple calculations that set the same variable, then especially
on RISC machines with multiple internal execution units, the
compiler might choose to use a "move conditional" instruction,
computing -both- results and then moving the proper result in
depending on the result of the comparison.

(Some chips have elaborate interlocks about exceptions that might be
generated in the meantime, holding on to exceptions and only releasing
them when the appropriate instruction would be "fully graduated", and
discarding them if it turns out that that section wasn't executed
after-all.)
--
Feep if you love VT-52's.
Nov 14 '05 #13
Nothing to add to what has been already said, except this:
I have been writing a lot of software, some very computation intensive,
and some with tight real-time requirements.

I have never ever had to bother with the speed of integer tests, except
maybe on some microcontrollers and way back on Z80 processors (4 MHz,
this does blow your mind doesn't it?) And even in those cases, I would
write routines in assembly language if speed was really a concern.

That said, even the dumbest C compiler will compile this kind of test
in the optimal way. You'd need to get a very, very old compiler to
actually find a difference in the object code.
The same goes for integer multiply/divide by a power of 2. Except when
it is clearer to the reader, you don't need to use shifting operators.
Over 12 years ago, Think C on the Mac already knew how to optimize
n / 2 as a right shift operation.

So, as other have said, you're most likely to be wasting your time
with such questions...
Nov 14 '05 #14
On Wed, 18 May 2005 00:31:38 +0200, Guillaume
<> wrote:
I have never ever had to bother with the speed of integer tests, except
maybe on some microcontrollers and way back on Z80 processors (4 MHz,
this does blow your mind doesn't it?)
Indeed it does, when I used Z80 they didn't go nearly that fast! 1MHz
was usual...
And even in those cases, I would
write routines in assembly language if speed was really a concern.
Yup. Done that...
That said, even the dumbest C compiler will compile this kind of test
in the optimal way. You'd need to get a very, very old compiler to
actually find a difference in the object code.
The same goes for integer multiply/divide by a power of 2. Except when
it is clearer to the reader, you don't need to use shifting operators.
Over 12 years ago, Think C on the Mac already knew how to optimize
n / 2 as a right shift operation.
Even the Aztec C compiler on the 8080 did that (actually, at one point
it had a separate optimiser which you ran on the generated assembler!).
Since the 8080 didn't have multiply and divide instructions, this saved
an enormous amount of code and time getting rid of the calls to compiler
support functions...
So, as other have said, you're most likely to be wasting your time
with such questions...


Indeed. But retro-programming is fun <g>...

Chris C
Nov 14 '05 #15
On Wed, 18 May 2005 00:31:38 +0200, Guillaume <"grsNOSPAM at
NOTTHATmail dot com"> wrote:

<snip>
The same goes for integer multiply/divide by a power of 2. Except when
it is clearer to the reader, you don't need to use shifting operators.
Over 12 years ago, Think C on the Mac already knew how to optimize
n / 2 as a right shift operation.

_For unsigned integers_. For signed, the round-in required in C99 and
universally or nearly so implemented though not required in C89,
differs from and thus can't be optimized to right shift on two's
complement which also is nearly universal but not actually required.

For signed but actually positive values, usually something like i/2U
will conveniently give a correct and optimizable result.

- David.Thompson1 at worldnet.att.net
Nov 14 '05 #16
On Mon, 23 May 2005 02:31:37 GMT,
Dave Thompson <da*************@worldnet.att.net> wrote:

On Wed, 18 May 2005 00:31:38 +0200, Guillaume <"grsNOSPAM at
NOTTHATmail dot com"> wrote:

<snip>
The same goes for integer multiply/divide by a power of 2. Except when
it is clearer to the reader, you don't need to use shifting operators.
Over 12 years ago, Think C on the Mac already knew how to optimize
n / 2 as a right shift operation.

_For unsigned integers_. For signed, the round-in required in C99 and
universally or nearly so implemented though not required in C89,
differs from and thus can't be optimized to right shift on two's
complement which also is nearly universal but not actually required.


Thus, compilers which optimizes divide by 2 to shift the value right will
first test if the value is negative. If it is, the value is then negated
before shift and then the result is negated to get the negative result.

Villy
Nov 14 '05 #17
In article <dn********************************@4ax.com>,
Dave Thompson <da*************@worldnet.att.net> wrote:
On Wed, 18 May 2005 00:31:38 +0200, Guillaume <"grsNOSPAM at
NOTTHATmail dot com"> wrote:

<snip>
The same goes for integer multiply/divide by a power of 2. Except when
it is clearer to the reader, you don't need to use shifting operators.
Over 12 years ago, Think C on the Mac already knew how to optimize
n / 2 as a right shift operation.
_For unsigned integers_. For signed, the round-in required in C99 and
universally or nearly so implemented though not required in C89,
differs from and thus can't be optimized to right shift on two's
complement which also is nearly universal but not actually required.


Ok, make that two instructions on a PowerPC for signed integers (one
shift right arithmetic, one add zero + carry).
For signed but actually positive values, usually something like i/2U
will conveniently give a correct and optimizable result.

- David.Thompson1 at worldnet.att.net

Nov 14 '05 #18

"tigervamp" <rg*******@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
junky_fel...@yahoo.co.in wrote:
which of the following is faster and why ?

if ( x == 1 ) {

}

or

if ( x != 0 ) {

}


It depends on your platform, the Standard has nothing to say about
this. Why don't you test it yourself on your machine?

You should also note that the above tests are not equivalent. If x is
2 then the first test will be false while the second will be true. You
should be more worried about writing clear code that makes sense in
your situation and let the compiler worry about how to best perform the
test for you since it undoubtedly knows more than you do about how best
to optimize such an expression.

Rob Gamble


I have fixed many a line of code where someone or some program tried to
convert a program from a language which assumed the low order bit to be
"true". It is not always easy to find on an embedded system :-).
Nov 14 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number....
5
by: MLH | last post by:
I have a table I can open as table type recordset or a dynaset. Searching for a particular value in the table's main keyfield, which would be faster and less strain on the application......
65
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second...
14
by: Bob | last post by:
I have a function that takes in a list of IDs (hundreds) as input parameter and needs to pass the data to another step as a comma delimited string. The source can easily create this list of IDs in...
7
by: Sunil Varma | last post by:
Is accessing function by it's name faster or accessing it by its address faster?
4
by: Sonnich | last post by:
Hi I have a costum function for a special search, which sort strings. This is currently the place where I can save a lot of time (~70%) if possible. So, which is faster: for($j =...
25
by: Ganesh | last post by:
Hi, This is a question that pertains to pointers in general (C or C++). Which of the following is faster and why? for (int i = 0; i < N; i++) = ... a... (or)
8
by: Sing | last post by:
Dear C Gurus, I would like to optimise a max() algo that my program uses many times. Which one is faster or are they the same? 1. #define max(a,b) (((a) (b)) ? (a) : (b)) 2. if (a>b) return a...
36
by: lak | last post by:
Which is faster? Post Increment or assignment? Why? I was not able to get any things.
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.