473,654 Members | 3,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

try/catch on dequeue is way slower than my own lock

Using a synchronized Queue, I did some testing on catching the "queue
was empty on dequeue" exception vs. doing my own lock, checking for
empty, and then dequeuing. The try/catch method, though simpler in
code, was 100x slower than doing my own empty-check before dequeue.
That seems incredible to me that the try/catch handlers could be that
much slower than a lock and an empty check. It makes me want to go
through the codebase and rip out all the try-catch blocks that I
possibly can. Was it because I was running in the debugger? Would it
be better if I compiled in release mode?

Feb 5 '07 #1
5 3106
On Feb 5, 10:48 am, "not_a_comm ie" <notacom...@gma il.comwrote:
Using a synchronized Queue, I did some testing on catching the "queue
was empty on dequeue" exception vs. doing my own lock, checking for
empty, and then dequeuing. The try/catch method, though simpler in
code, was 100x slower than doing my own empty-check before dequeue.
That seems incredible to me that the try/catch handlers could be that
much slower than a lock and an empty check. It makes me want to go
through the codebase and rip out all the try-catch blocks that I
possibly can. Was it because I was running in the debugger? Would it
be better if I compiled in release mode?
Without seeing some code it's difficult to say. IMO, if you can check
whether or not the queue is empty, then do so rather than relying on
the exception because exceptions are slower.

Can you show a short but complete program which illustrates your
problem?

Chris

Feb 5 '07 #2
IMO, you can't reliably check for empty condition anyway unless you take the
lock first and do your check. You need the lock anyway if there is item, so
take the lock being optimistic there is some data. You could use Count as a
hint for non-critical/non-atomic operations, but don't rely on it unless
your inside the lock. Couple ways to go on empty. 1) you can throw error.
2) you can return a default(T) and let caller deside what to do. 3) you can
block till some item appears. It depends on your collection and what you
want your api to do. I normally prefer a Tryxxx method if possible so I can
avoid the error condition and get explicit condition if queue is really
empty and not have to guess on what default(T) means.

--
William Stacey [C# MVP]
PCR concurrency library: www.codeplex.com/pcr
PSH Scripts Project www.codeplex.com/psobject
"not_a_comm ie" <no********@gma il.comwrote in message
news:11******** **************@ v45g2000cwv.goo glegroups.com.. .
| Using a synchronized Queue, I did some testing on catching the "queue
| was empty on dequeue" exception vs. doing my own lock, checking for
| empty, and then dequeuing. The try/catch method, though simpler in
| code, was 100x slower than doing my own empty-check before dequeue.
| That seems incredible to me that the try/catch handlers could be that
| much slower than a lock and an empty check. It makes me want to go
| through the codebase and rip out all the try-catch blocks that I
| possibly can. Was it because I was running in the debugger? Would it
| be better if I compiled in release mode?
|
Feb 5 '07 #3
not_a_commie <no********@gma il.comwrote:
Using a synchronized Queue, I did some testing on catching the "queue
was empty on dequeue" exception vs. doing my own lock, checking for
empty, and then dequeuing. The try/catch method, though simpler in
code, was 100x slower than doing my own empty-check before dequeue.
That seems incredible to me that the try/catch handlers could be that
much slower than a lock and an empty check. It makes me want to go
through the codebase and rip out all the try-catch blocks that I
possibly can. Was it because I was running in the debugger? Would it
be better if I compiled in release mode?
If you're running in a debugger, that will indeed make exceptions
significantly slower than not in a debugger.

However, this is an abuse of exceptions - you can easily check for the
queue being empty, so don't just "hit and hope".

You should indeed go through your code if you have a lot of try/catch
blocks - but more for design reasons than performance. Generally you
should have far more try/finally blocks (usually in the form of using
statements) than try/catch blocks. If you're regularly doing try/catch
for something which you can test beforehand, that's a design flaw IMO.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 5 '07 #4
Can you show a short but complete program which illustrates your
problem?
Here she be. I would also appreciate it if you could confirm that I'm
doing the locking correctly. I need the AddItem function to run in one
thread and GetPriorityItem function to run in a different thread. It
seems that running outside the debugger is significantly faster at
exceptions, but still way slower than otherwise. I'm still entirely
astounded at how drastic the difference is between the two.

using System;
using System.Collecti ons.Generic;
using System.Text;
using System.Collecti ons;
using System.Diagnost ics;

namespace QueueDemoApp
{
class Program
{
class LeveledQueue
{
Queue[] queues;
public LeveledQueue(ui nt numPriorities)
{
queues = new Queue[numPriorities];
for(int i = 0; i < numPriorities; i++)
queues[i] = Queue.Synchroni zed(new Queue());
}
public void AddItem(uint priority, object item)
{
if (priority < queues.Length)
queues[priority].Enqueue(item);
}
public object GetHighestPrior ityItemFast()
{
for (int i = queues.Length - 1; i >= 0; i--)
{
Queue q = queues[i];
lock (q.SyncRoot) // same lock as the Dequeue/
Enqueue use?
{
if (q.Count 0)
return q.Dequeue();
}
}
return null;
}
public object GetHighestPrior ityItemSlow()
{
for (int i = queues.Length - 1; i >= 0; i--)
{
Queue q = queues[i];
try
{
object ret = q.Dequeue();
return ret;
}
catch (InvalidOperati onException) { }
}
return null;
}
}
static void Main(string[] args)
{
LeveledQueue lq = new LeveledQueue(16 );
// worst case will be when they have no data

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 4000; i++)
{
object obj = lq.GetHighestPr iorityItemFast( );
}
sw.Stop();
Console.WriteLi ne("Fast call used {0} seconds for 4k",
sw.Elapsed.Tota lSeconds);
sw.Reset();
sw.Start();
for (int i = 0; i < 4000; i++)
{
object obj = lq.GetHighestPr iorityItemSlow( );
}
sw.Stop();
Console.WriteLi ne("Slow call used {0} seconds for 4k",
sw.Elapsed.Tota lSeconds);
}
}
}
Feb 6 '07 #5
not_a_commie <no********@gma il.comwrote:
Can you show a short but complete program which illustrates your
problem?

Here she be. I would also appreciate it if you could confirm that I'm
doing the locking correctly. I need the AddItem function to run in one
thread and GetPriorityItem function to run in a different thread. It
seems that running outside the debugger is significantly faster at
exceptions, but still way slower than otherwise. I'm still entirely
astounded at how drastic the difference is between the two.
Well, the locking is correct - and is the right way to go. Exceptions
aren't meant to be used the way you're using them. They're meant to be
used for *exceptional* situations. If the logic of your program should
make it an error for the queue to be empty, you should try to dequeue
and *not* catch the exception there, but much higher up. If, however,
the logic of your program doesn't try to stop the queue from being
empty, then you shouldn't use an exception at all. Your "fast" version
is exactly the right way of doing things.

Admittedly I'd just do:

return q.Count 0 ? q.Dequeue() : null;

but the effect is the same.
Any time you want to catch an exception and just swallow it, you should
re-examine your design. It *may* be appropriate (the situation may be
forced on you by a library you're using, for instance) but usually it's
a bad sign.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 6 '07 #6

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

Similar topics

6
552
by: Erik Cruz | last post by:
Hi. I have read several articles recommending avoid to raise exceptions when possible, since exceptions are expensive to the system. Removing code from Try... Catch blocks can help performance? The following 2 first lines of code - I think - can't raise exceptions: Try Dim str As String Dim intVar As Integer
27
1481
by: Gernot Frisch | last post by:
Is it faster to define a vertex structure by .x .y .z members instead of array? -- -Gernot int main(int argc, char** argv) {printf ("%silto%c%cf%cgl%ssic%ccom%c", "ma", 58, 'g', 64, "ba", 46, 10);} ________________________________________ Looking for a good game? Do it yourself!
0
2025
by: Bryan Olson | last post by:
New and improved! Love Python's stack-tracing error messages, but hate the way GUI applications throw the messages away and crash silently? Here's a module to show Python error messages that would otherwise be lost in console-less programs. Graphical applications should not require console windows, but they do need a workable destination for sys.stderr.
9
1759
by: Dmitriy Lapshin [C# / .NET MVP] | last post by:
Hi all, When a good developer should declare an exception variable in a catch clause? Consider an example: try { // Do something potentially dangerous... } catch(SomeException e)
6
7124
by: Tilfried Weissenberger | last post by:
Hi, I am a bit confused as to what the FINALLY block is meant for. What's the difference between: this.Cursor = Cursors.WaitCursor; try { //do some stuff } catch { //handle exception } finally { this.Cursor = Cursors.Default; }
7
5393
by: BC | last post by:
Hi all, I have a method that accepts a string as the parameter. This can be a base64 image string, or just a normal string. Currently to test whether it's a image string or just a normal string, I used try and catch: private void MyMethod(string str){ try{ // If not exception is cought, then it is an image string MemoryStream stream = new MemoryStream(Convert.FromBase64String(str));
4
6331
by: Benny Raymond | last post by:
It's currently taking a minimum of .2 seconds for me to dequeue an object - I'm wondering if it's the dequeue that is taking so long or if it's just the fact that i'm doing it like this: retMsg = (ServerMessage)s_messages.Dequeue(); is there a faster way?
1
2385
by: buu | last post by:
If I have a code like: TRY SYNCLOCK Object1 //some code END SYNCLOCK CATCH END TRY
0
8379
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, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8294
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
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8596
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
7309
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...
0
4297
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2719
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1924
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1597
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.