473,765 Members | 2,061 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Which one is better in performance - a for loop or a while loop?

12 New Member
I wanted to know which one is better in performance between a for loop and a while loop in terms of:
1. memory requirement
2. execution speed

Also wanted to know since recursion functions are not as efficient as for of while in terms of memory requirement and execution speed, what is the purpose of using them in the code?
Sep 1 '10 #1
8 5939
MartijnHoekstra
39 New Member
Hi with regards to while and for:
- Memory requirement: The loops themselves cost no memory other than the jump statements, neglectable.
- Execution speed: for simple expressions there will be no difference. But for advanced criteria to keep a loop running, a while loop could be more efficient. For example by use of switch cases or single if statements to break out of the loop.

Recursions are in some cases necessary for special features, which otherwise would require extensive iterational coding.
Best known example would be the solution to solve the 'towers of hanoi'.
The efficiency will then be at development level. But at execution time, the efficiency loss will only be due to the call-stack.
Sep 1 '10 #2
donbock
2,426 Recognized Expert Top Contributor
I can't think of any reason for there to be a time- or space-efficiency difference between for and while loops.
Sep 1 '10 #3
donbock
2,426 Recognized Expert Top Contributor
If the loop body is executed N times, then for/while will evaluate the termination expression N+1 times but do while will only evaluate it N times.
Sep 1 '10 #4
Oralloy
988 Recognized Expert Contributor
The main difference between the for/while and the do while is when the test is executed.

Let's leave out the for loop's initializer and iteration; they will have to be coded when using while loops anyway.

The only difference is that do while condition does not guard the first execution pass through the body of the loop. Said loop will always execute its body at least once.

In the for and while loops, the condition is executed before the first pass through the body of the loop - meaning that the body of the loop is guarded against inadvertent execution.

Set that aside, do while has fallen into general disfavor for a number of reasons, as the goto has. That is not to say that it does not have its place and value, just that it's in disfavor. Likely because when people write long (e.g. 100 line) loop bodies, it's very easy to lose track of the termination condition.

Still, do while has its place, and belongs in your tool-kit.
Sep 1 '10 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
I don't see that do/while has fallen out of favor.

It is just a loop you use when you want the loop to execute at least once.
Sep 2 '10 #6
Oralloy
988 Recognized Expert Contributor
weakness,

I'm perhaps biased, but I've not seen it used in industrial code more than a dozen times in 25 years of experience.

Now, I will admit that I've seen people go to ungodly lengths to simulate the do while, but actual use, almost never.

Cheers!

prrrrrr
Sep 2 '10 #7
weaknessforcats
9,208 Recognized Expert Moderator Expert
I usuaally see this in menu processing where you want the user to provide a choice.

If you use a while loop you need to get a choice outside the loop the first time and inside the loop the rest of the time. The do loop avoids the extra code.
Sep 4 '10 #8
Oralloy
988 Recognized Expert Contributor
Weakness,

I do understand.

Most of what I've worked with is machine control and GUI interfaces. Lots of interrupt driven code and state machines.

Thank you for the insight. I do appreciate it.

Cheers!
Sep 7 '10 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1431
by: Mike | last post by:
Right now I run mysql and apache together on a dual p3 1.3ghz box. I will be moving mysql to a second box, eather an identical dual p3 box or spending a little more and going for a single Xeon 3Ghz (these are the only two options I have). I'm thinking of hanging the db box behind the webserver using a gigabit crossover. Since I mostly read cached data, I'm leaning towards the dual CPU box so that when I have a long running query thats...
1
1533
by: Jason | last post by:
Hi all, I have 1 table which need to store 7 days data in a row, I not sure which table design will gain better performance in SELECT statement. Desgin 1. 7 columns (day1, ..., day7) with char(4) or Desgin 2. 1 column (day_1_to_7) with char(28); to retrieve the data, use substr function Plz advise. Thanks!
3
2031
by: davihigh | last post by:
Hi Friends: I am managing a large number of objects which has unique id <ULONG64>. Which container i should choose to perform best find() performance? Can choose from STL in vc2003 or Boost 1_33. Currently I am using std::map<>. Your suggestion? Rgds, David Xiao
1
1557
by: Tommy | last post by:
The problem is how to achieve the transformation as below: The source xml contains tons of repeating structure like below, each item node contains a person element and a insurance element that correlate to the Person element with the person id. <Item> <Person id=”p123” name=”someone1”> <Insurance ref=”p123” detail=”blabla1”> </item> <Item>
8
3273
by: shumaker | last post by:
I'm wondering if adding an autonumber primary key will improve the performance of a multiuser access database on a network share. I have a website that lists many tips for improving performance of access, but doesn't mention primary keys. However, it seems logical to think that having no primary key means that when a user updates a record, the database has to do comparisons on multiple fields to identify the specific record being...
1
1393
by: prileep | last post by:
I have two tables Users and UserLogin. Here i will use two methods of table design. and which query will return me the result more fast. The table size will be large that it may contain records in lakhs. Method 1: Tables: Users ( UserID varchar(20) primary key, PassWord varchar(20)) UsersLogin(UserID varchar(20),LoginDate DateTime) Query: Select Users.UserID,UsersLogin.LoginDate from Users U inner join UsersLogin UL
1
9670
by: imani_technology_spam | last post by:
Right now, a client of mine has a T-SQL statement that does the following: 1) Create a temp table. 2) Populate temp table with data from one table using an INSERT statement. 3) Populate temp table with data from another table using an INSERT statement. 4) SELECT from temp table.
2
1220
by: krishhhna | last post by:
Hi, I have a doubt on procedure and function's,that is nI have one procedure that returns one value and function which also returns only one value. which one is better to use ,either procedure or function??
2
1492
by: Franck Y | last post by:
Hello Folks, I am facing a problem where i need to parse around 200 files, i have a bit of knowledge in PHP/Perl/Python (the magic P :-P) Which one would you suggest me since i have to generate a web interface ? And each one has his area of 'work'
2
1213
by: getmeidea | last post by:
I have the folowing two tables. employee_master( emp_rid int primary key identity, emp_no char(20) not null, emp_name varchar(100) ); salary_payment( sp_rid int primary key,
0
9568
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
9404
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10008
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...
0
9837
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...
0
8833
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5279
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.