473,738 Members | 10,068 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

WHILE loop speed compared to cursors?

Working on some new code, I'm coming across WHILE loops used instead of
cursors. I was curious if anyone had any stats on how the speed of
doing this compares to the speed of a cursor. I typically avoid
cursors for performance sake, but I'm not sure how this avoids the
speed hit of a cursor, since it's doing essentially the same thing.

Many thanks.

Jul 23 '05 #1
4 10745
A WHILE loop is a cursor by another name. Why can't you write set-based
code and avoid cursors in either form?

--
David Portas
SQL Server MVP
--

Jul 23 '05 #2
My experience is that using a WHILE loop, if applicable, is generally
faster than using cursors.

I rewrote a coworkers cursor code that did a simple concatenation of a
column across groups. It took about 15 minutes to perform before with
a cursor, and with the WHILE loop it took 12 seconds.

In some/other cases, I'm sure WHILE would not work better.

SQL Server cursors are notoriously inefficient. I've seen examples
where people have rewritten cursor code to pull a data into a c#
program via ADO.NET, process the records, and write them back to the
database. It was about ten times faster than equivalent cursor code.

My only guess as to why cursors are so inefficient is that they are
interpreted, not compiled code.

Jul 23 '05 #3
Gary (ga**********@w cc.ml.com) writes:
My experience is that using a WHILE loop, if applicable, is generally
faster than using cursors.

I rewrote a coworkers cursor code that did a simple concatenation of a
column across groups. It took about 15 minutes to perform before with
a cursor, and with the WHILE loop it took 12 seconds.

In some/other cases, I'm sure WHILE would not work better.

SQL Server cursors are notoriously inefficient. I've seen examples
where people have rewritten cursor code to pull a data into a c#
program via ADO.NET, process the records, and write them back to the
database. It was about ten times faster than equivalent cursor code.

My only guess as to why cursors are so inefficient is that they are
interpreted, not compiled code.


The default cursor type in SQL Server is keyset-driven. I've never
understood what this means, but I always add INSENSITIVE before the
cursor name. Not doing this, have sometimes given me horrible query
plans for the query in the cursor. (This was in 6.5, but I'm not
going to try in SQL 2000.) INSENSITVE means that the cursor set is
fixed and copied to some work area.

I maintain that if you need to iterate - and sometimes you do - then
a cursor is the best way to go. I have caught several of my colleagues
red-handed when they've gone for things like:

WHILE @id IS NOT NULL
BEGIN
SELECT @id = MIN(id) FROM #tmp WHERE id = @id
IF @id IS NOT NULL
BEGIN
SELECT @this = this, @that = that ... FROM #tmp WHERE id = @id

And I've caught them when their code has caused performance issues,
because the temp table had more rows than they had anticipated, and
they had not indexed the id column. Well, with a cursor they would
not have needed the index anyway.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #4
Thanks for the info, everyone. Unfortunately, this is one of the times
when I do need to iterate, so I'll take a look and see how a cursor
would compare.
Erland Sommarskog wrote:
I maintain that if you need to iterate - and sometimes you do - then
a cursor is the best way to go.


Jul 23 '05 #5

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

Similar topics

2
22711
by: Jeremy Moncho | last post by:
Hi guys, I am having a comprehension problem for which I cannot seem to find an answer (by banging my head on my keyboard.) I have the following code which yields no results. I expect one result to come out of it as I am using a while loop on a cursor set to retrieve one single tuple. Please be nice, it is my first day seeing cursors ;-)
3
9478
by: RobG | last post by:
A little while ago I opined that do/while loops are harder to read than for loops, and therefore I preferred using for loops. However, it was pointed out that do/while has significant performance benefits as evidenced by: <URL:http://www.websiteoptimization.com/speed/10/10-2.html> (There's a bug in the page, testLoop is both a function name and the name of the form but if you download the page & rename
6
1882
by: km | last post by:
Hi all, Why is it that the implementation of empty loop so slow in python when compared to perl ? #i did this in python (v 1.5) for x in xrange(1000): print x # this took 0.017 seconds -------------------------- #similar code in perl (v 5.6):
15
2676
by: Mike Lansdaal | last post by:
I came across a reference on a web site (http://www.personalmicrocosms.com/html/dotnettips.html#richtextbox_lines ) that said to speed up access to a rich text box's lines that you needed to use a "foreach" loop instead of a "for" loop. This made absolutely no sense to me, but the author had posted his code and timing results. The "foreach" (a VB and other languages construct) was 0.01 seconds to access 1000 lines in rich text box,...
102
4542
by: tom fredriksen | last post by:
Hi I was doing a simple test of the speed of a "maths" operation and when I tested it I found that removing the loop that initialises the data array for the operation caused the whole program to spend twice the time to complete. If the loop is included it takes about 7.48 seconds to complete, but when removed it takes about 11.48 seconds. Does anybody have a suggestion as to why this is so and whether I can trust the results of the...
16
3532
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g.
20
1730
by: Steven D'Aprano | last post by:
Am I the only one who finds that I'm writing more documentation than code? I recently needed to write a function to generate a rank table from a list. That is, a list of ranks, where the rank of an item is the position it would be in if the list were sorted: alist = list('defabc') ranks = To do that, I needed to generate an index table first. In the book
0
438
by: =?ISO-8859-1?Q?Gerhard_H=E4ring?= | last post by:
Steve Holden wrote: No, I just find code like: con = ...connect(...) cursor1 = con.cursor() cursor1.execute("select ...") for row in cursor1: cursor2 = con.cursor() cursor2.execute("...)
2
2893
by: alireza6485 | last post by:
Hi, Could you please rewrite the program for me?I tried my best and the program still does not do what it has to do. I have to write a code that generates random speed and distance .it ask the user for angle and start calculating the vertical and horizantal positions. when the vertical position gets negative program should stop and check the horizantal position and print out different messeges based on the value of the horizantal speed. ...
0
8788
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
9335
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
9263
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
9208
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
8210
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 project—planning, coding, testing, and deployment—without 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...
1
6751
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
6053
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
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2193
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.