473,385 Members | 1,893 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,385 software developers and data experts.

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 3092
On Feb 5, 10:48 am, "not_a_commie" <notacom...@gmail.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_commie" <no********@gmail.comwrote in message
news:11**********************@v45g2000cwv.googlegr oups.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********@gmail.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.com>
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.Collections.Generic;
using System.Text;
using System.Collections;
using System.Diagnostics;

namespace QueueDemoApp
{
class Program
{
class LeveledQueue
{
Queue[] queues;
public LeveledQueue(uint numPriorities)
{
queues = new Queue[numPriorities];
for(int i = 0; i < numPriorities; i++)
queues[i] = Queue.Synchronized(new Queue());
}
public void AddItem(uint priority, object item)
{
if (priority < queues.Length)
queues[priority].Enqueue(item);
}
public object GetHighestPriorityItemFast()
{
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 GetHighestPriorityItemSlow()
{
for (int i = queues.Length - 1; i >= 0; i--)
{
Queue q = queues[i];
try
{
object ret = q.Dequeue();
return ret;
}
catch (InvalidOperationException) { }
}
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.GetHighestPriorityItemFast();
}
sw.Stop();
Console.WriteLine("Fast call used {0} seconds for 4k",
sw.Elapsed.TotalSeconds);
sw.Reset();
sw.Start();
for (int i = 0; i < 4000; i++)
{
object obj = lq.GetHighestPriorityItemSlow();
}
sw.Stop();
Console.WriteLine("Slow call used {0} seconds for 4k",
sw.Elapsed.TotalSeconds);
}
}
}
Feb 6 '07 #5
not_a_commie <no********@gmail.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.com>
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
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?...
27
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,...
0
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...
9
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
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 }...
7
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,...
4
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...
1
by: buu | last post by:
If I have a code like: TRY SYNCLOCK Object1 //some code END SYNCLOCK CATCH END TRY
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
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...

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.