473,657 Members | 2,591 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does 'if' have performance overhead

Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
>From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.

However, i am bit skeptic about this.
I need some guidance. Performance is always the key issue for me when
it comes to writing programs.

Please guide.

Oct 16 '07 #1
12 4794
la******@gmail. com wrote:
Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
Somewhat true, I hear.

It's not the if-statement per se. It's the fact that control flow of the
program branches.

From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.
That is a Bad Idea(tm).

Optimizations avoiding if-statements are usually non-obvious and change the
nature of your code fundamentally. To see that, just try to rewrite

unsigned int max ( unsigned int lhs, unsigned int rhs );

without branch statements. Generally, avoiding branch statements can be
considered code obfuscation. Code obfuscation for the sake of performance
gains that have not proven necessary by profiling is a form of premature
optimization.

However, i am bit skeptic about this.
What do your measurements tell you?

I need some guidance. Performance is always the key issue for me when
it comes to writing programs.
It should not be. Programmer time is much more expensive than CPU time. The
rational choice is to optimize for code beauty, extendability, ease of use,
and maintenability.
Best

Kai-Uwe Bux
Oct 16 '07 #2
<la******@gmail .comwrote in message
news:11******** **************@ q3g2000prf.goog legroups.com...
Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
>>From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.

However, i am bit skeptic about this.

I need some guidance. Performance is always the key issue for me when
it comes to writing programs.

Please guide.
You should not prematurely optimize. That is, don't attempt to optimize
code until you find what is actually taking the time.

if statements are extremly common in code in all languages They essentially
come down to a jump in the CPU based on some condition (jump if not zero,
jump if greater than zero, etc...). Now, I believe you are talking about
prefetching instructions and that he CPU won't know what set of instructions
to prefetch if there is a jump, set A or set B.

A lot of times the compiler itself may optimize the code, and a lot of times
the CPUs are smart enough to either figure it out or prefetch both branches.
In other words, I would not worry about if statments taking up too much
time. Although I wouldn't throw in if statments for no reason either.
Oct 16 '07 #3
On 2007-10-16 07:25, la******@gmail. com wrote:
Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
This is totally off topic:

That is only partially true one a modern PC processor (as opposed to
embedded processors which I have little knowledge about) since they all
have pretty good branch prediction these days. This is best demonstrated
by a simple loop:

for (int i = 0; i < 10; ++i)
{
// do stuff
}
// do other stuff

The processor recognises a loop when it sees one, and it will assume
that you will perform the iterations, so the loop can be optimised very
well. The problem comes when the last iteration is done, since the
processor wrongly assumes that you will iterate you get a small
performance hit when it discovers that you do not.

Similarly the processor can optimise if statements and other control
statements. Even better, they can learn, so if you have an if statement
and you time after time go to the else clause the processor will
remember this and will start executing the else clause when reaching the
if statement before the comparison is complete. Again, should it happen
that the assumption is wrong you get a performance hit.

Notice though that this performance hit is less noticeable on modern
hardware than is was on a P4, since the processors of today are not as
deeply pipelined.
>>From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.
The best way to optimise an if statement is to write the code that is
most likely to be executed in the if clause and the least likely in the
else clause, since that will save the processor a jump in most cases.
However, i am bit skeptic about this.
Rightly you should be, you should be sceptic about any optimisation that
is not at the algorithmic level.
I need some guidance. Performance is always the key issue for me when
it comes to writing programs.
Select the best algorithms and data structures for the task and then use
a good profiler.

--
Erik Wikström
Oct 16 '07 #4
On Oct 16, 2:04 pm, Erik Wikstrm <Erik-wikst...@telia. comwrote:
On 2007-10-16 07:25, lali....@gmail. com wrote:
Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.

This is totally off topic:

That is only partially true one a modern PC processor (as opposed to
embedded processors which I have little knowledge about) since they all
have pretty good branch prediction these days. This is best demonstrated
by a simple loop:

for (int i = 0; i < 10; ++i)
{
// do stuff
}
// do other stuff

The processor recognises a loop when it sees one, and it will assume
that you will perform the iterations, so the loop can be optimised very
well. The problem comes when the last iteration is done, since the
processor wrongly assumes that you will iterate you get a small
performance hit when it discovers that you do not.

Similarly the processor can optimise if statements and other control
statements. Even better, they can learn, so if you have an if statement
and you time after time go to the else clause the processor will
remember this and will start executing the else clause when reaching the
if statement before the comparison is complete. Again, should it happen
that the assumption is wrong you get a performance hit.

Notice though that this performance hit is less noticeable on modern
hardware than is was on a P4, since the processors of today are not as
deeply pipelined.
>From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.

The best way to optimise an if statement is to write the code that is
most likely to be executed in the if clause and the least likely in the
else clause, since that will save the processor a jump in most cases.
However, i am bit skeptic about this.

Rightly you should be, you should be sceptic about any optimisation that
is not at the algorithmic level.
I need some guidance. Performance is always the key issue for me when
it comes to writing programs.

Select the best algorithms and data structures for the task and then use
a good profiler.

--
Erik Wikstrm
Thank you very much for your response.

lali

Oct 16 '07 #5
On Mon, 15 Oct 2007 22:25:22 -0700, lali.b97 wrote:
Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot agressively
optimize that code.
>>From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.

However, i am bit skeptic about this.
I need some guidance. Performance is always the key issue for me when it
comes to writing programs.

Please guide.
I wouldn't worry about it. If I wanted to avoid if statements in my code
I'd be in serious trouble. Only worry about optimizing what actually
needs optimizing.

To give you an example, I am working on a 2D CAD application for
electronics design. At the lowest level, I have a class called Scalar
that allows me to perform arithmetic with any 2 values, regardless of
unit type (inch, millimeter, etc.) with one another.

This being among the most essential and lowest-level class of them all,
it has every bit imaginable optimized out of it that I can think of.
Because even a single instruction saved in this class can translate into
hundred thousands or more instructions during a complex operation later
on. Here, speed matters more to me than code clarity.

Maybe I should sell it to NASA so that they can stop crashing things into
planets because they can't get their units straight. =)

Now, my higher level functions though, such as the code that can take 2
object outlines composed of line and curve segments and calculate the
distance or intersection between the two outlines, is somewhat optimized
but I don't overly worry about squeezing every last bit out of it. In a
worst case scenario this code might maybe be called a hundred or so times
in one shot. Clearly written code at the expense of speed is more
important here as it involves some complex operating.

So what I'm trying to get at is, unless the code is really speed critical
and you absolutely will benefit from every tiniest bit of optimization,
don't worry about it. Rather worry that your code is clearly written in a
way that you can still understand it when you come back to it 6 months
later. That'll benefit you far more. =)

--
Stephan
2003 Yamaha R6

君のこと思 い出す日な んてないの は
君のこと忘 れたときが ないから
Oct 17 '07 #6
la******@gmail. com wrote:
Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
>>From that day onwards i have been trying to avoid if statement withing
my functions as much as possible and also try to have minimum code
withing if block.
You are making the classic mistake: Believing something you read and
starting blindly doing it that way without actually *testing* it in
practice.

I may well be that your avoidance of the if clause may in fact be
producing slower code. However, since you haven't tested both
possibilities in your programs, you can't know.

Anyways, in the vast majority of cases such a small potential
optimization doesn't matter at all. Usually less than 1% of a program
which performs heavy calculations would require such low-level
optimization (if even that much).
Oct 17 '07 #7
In message <ff**********@m urdoch.acc.Virg inia.EDU>
Kai-Uwe Bux <jk********@gmx .netwrote:
la******@gmail. com wrote:
>Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
It takes more time? I'm not sure how you would measure that! Surely
not by sitting in front of the screen with a stop-watch?

The only workable thing I can think of is to put a line before the
block under test to read the internal clock, a second line at the end
of the block, and the difference is the time taken. How exactly would
you do such a thing?

Michael Bell

--
Oct 18 '07 #8
In message <ff**********@m urdoch.acc.Virg inia.EDU>
Kai-Uwe Bux <jk********@gmx .netwrote:
la******@gmail. com wrote:
>Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.
It takes more time? I'm not sure how you would measure that! Surely
not by sitting in front of the screen with a stop-watch?

The only workable thing I can think of is to put a line before the
block under test to read the internal clock, a second line at the end
of the block, and the difference is the time taken. How exactly would
you do such a thing?

Michael Bell

--
Oct 19 '07 #9
On Fri, 19 Oct 2007 07:33:09 +0100, Michael Bell wrote:
In message <ff**********@m urdoch.acc.Virg inia.EDU>
Kai-Uwe Bux <jk********@gmx .netwrote:
> la******@gmail. com wrote:
>>Somewhere in a tutorial i read that if statement has performance
overheads as code within the if statement cannot take benefit of
pipeling of microprocessor and also that the compiler cannot
agressively optimize that code.

It takes more time? I'm not sure how you would measure that! Surely not
by sitting in front of the screen with a stop-watch?

The only workable thing I can think of is to put a line before the block
under test to read the internal clock, a second line at the end of the
block, and the difference is the time taken. How exactly would you do
such a thing?
That is a little platform dependent really.

In my case, I have a class called CpuTimer that works both under Windows
and Linux that can do high precision timing.

Then when I want to profile something, I will usually isolate the one
single function I want to profile, write a small test case along with
test data. The amount of data I generate depends on the complexity of the
function, that can range anywhere from a few hundred data items to a few
million.

Then I measure the time it took to process the complete data set, which
then divided by the number of data items in the set gives me the average
execution time per function call.

It's not 100% precise of course as too many uncontrollable factors can
affect execution speed, such as OS background tasks and such. However, it
is good enough to tell if a change I have made has made things better or
worse which is ultimately the only thing I am really concerned about.

--
Stephan
2003 Yamaha R6

君のこと思 い出す日な んてないの は
君のこと忘 れたときが ないから
Oct 19 '07 #10

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

Similar topics

30
3436
by: Christian Seberino | last post by:
How does Ruby compare to Python?? How good is DESIGN of Ruby compared to Python? Python's design is godly. I'm wondering if Ruby's is godly too. I've heard it has solid OOP design but then I've also heard there are lots of weird ways to do some things kinda like Perl which is bad for me. Any other ideas?
5
5517
by: John Edwards | last post by:
Hello, I have sort of a newbie question. I'm trying to optimize a loop by breaking it into two passes. Example: for(i = 0; i < max; i++) {
62
3364
by: christopher diggins | last post by:
Since nobody responded to my earlier post , I thought I would try to explain what I am doing a bit differently. When multiply inheriting pure virtual (abstract) base classes, a class obviously bloats quickly for each new vtable needed. Execution slows down considerably as well. You can work around this by using interfaces referemnces which have a pointer to the object and a pointer to an external function lookup table. This technique...
5
2579
by: Dmitry Martynov | last post by:
Consider I have the following construction "if(x is T) ...". How much this test cost? And I wonder how it is implemented. Can I gain in performace if I introduce virtual methods like "bool isIt...()" in my base class and then call them instead of using is-operator?
13
5035
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
6
6806
by: zl2k | last post by:
hi, there I am using a big, sparse binary array (size of 256^3). The size may be changed in run time. I first thought about using the bitset but found its size is unchangeable. If I use the vector<bool>, does each element takes 4 bytes instead of 1 bit? I am using gcc3.4.4. There is a bit_vector which is kind of old so I wont use that. Any other choices? Thanks ahead. zl2k
10
4279
by: shsandeep | last post by:
The ETL application loaded around 3000 rows in 14 seconds in a Development database while it took 2 hours to load in a UAT database. UAT db is partitioned. Dev db is not partitioned. the application looks for existing rows in the table...if they already exist then it updates otherwise inserts them. The table is pretty large, around 6.5 million rows.
34
2778
by: Creativ | last post by:
Why does Thread class not support IDisposable? It's creating quite some problem. Namely, it can exhaust the resource and you have not control over it.
2
2690
by: =?Utf-8?B?S2F1c2hhbCBNZWh0YQ==?= | last post by:
Hi, I am having this WCF application having one server and two clients. Is there any way I can perform performance analysis on the entire system including the networking overhead and the serialization overhead ? I tried the perfmon provided in the VS Team Edition, but I am not able to get the serialization as well as the networking overhead incured while sending messages accross.
0
8392
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8730
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6163
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1950
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1607
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.