473,396 Members | 2,089 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,396 software developers and data experts.

Remove from Hashtable? [easy one]

I'm often in a situation where I have a Hashtable full of objects. I'm
then presented with an object and *if* that object exists in the Hashtable,
I need to remove it from the table. I therefore have a lot of code that
looks like this:

if(ht.Contains(obj)){
ht.Remove(obj);
}

It strikes me that this code is somewhat inefficient because the
Hasthtable has to be searched *twice* : once for the Contains() call and
once for the Remove() call. So I thought maybe I should approach the
situation this way:

try{
ht.Remove(obj);
}
catch(Exception){}

Now I'm only searching the Hashtable once... but is the overhead of
throwing the exception cancelling out any benefit that I achieved by not
calling Contains()? To answer this question, you probably need to know how
frequently 'obj' is actually found in the Hashtable. For the sake of
argument, let's say 50%.

Thanks,

Jules
Nov 1 '05 #1
6 1505
Jules,

You can find this out easily. Why not run a few tests and time it?

If I had to guess, I would say that the overhead of determining if an
object exists in a hashtable is less than the overhead of catching the
exception.

Also, from a maintainability standpoint, it makes more sense, as you are
using exceptions to for programming logic, when a suitable construct is
already there.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Jules Winfield" <gh****@englewood.com> wrote in message
news:ur********************@giganews.com...
I'm often in a situation where I have a Hashtable full of objects. I'm
then presented with an object and *if* that object exists in the
Hashtable, I need to remove it from the table. I therefore have a lot of
code that looks like this:

if(ht.Contains(obj)){
ht.Remove(obj);
}

It strikes me that this code is somewhat inefficient because the
Hasthtable has to be searched *twice* : once for the Contains() call and
once for the Remove() call. So I thought maybe I should approach the
situation this way:

try{
ht.Remove(obj);
}
catch(Exception){}

Now I'm only searching the Hashtable once... but is the overhead of
throwing the exception cancelling out any benefit that I achieved by not
calling Contains()? To answer this question, you probably need to know how
frequently 'obj' is actually found in the Hashtable. For the sake of
argument, let's say 50%.

Thanks,

Jules

Nov 1 '05 #2

"Jules Winfield" <gh****@englewood.com> wrote in message
news:ur********************@giganews.com...
I'm often in a situation where I have a Hashtable full of objects. I'm
then presented with an object and *if* that object exists in the
Hashtable, I need to remove it from the table. I therefore have a lot of
code that looks like this:

if(ht.Contains(obj)){
ht.Remove(obj);
}

It strikes me that this code is somewhat inefficient because the
Hasthtable has to be searched *twice* : once for the Contains() call and
once for the Remove() call. So I thought maybe I should approach the
situation this way:

try{
ht.Remove(obj);
}
catch(Exception){}

Now I'm only searching the Hashtable once... but is the overhead of
throwing the exception cancelling out any benefit that I achieved by not
calling Contains()? To answer this question, you probably need to know how
frequently 'obj' is actually found in the Hashtable. For the sake of
argument, let's say 50%.

Thanks,

Jules


Also, you should not worry (too much) about performance when programming. It
is good practice to make the program, test it, and then deal with any
potential performance issues.

This is also due to the fact that the bottle necks usually are not in the
places you expect them to be, unless, of course, you are an experienced
programmer and you *know* this will be a bottle neck.

Experienced programmers call this premature optimizations.

Wait and see if searching the hash table twice takes a significant
percentage of your program's cpu time when the program is done, *then* deal
with it! :o)

The best,
Mogens
Nov 1 '05 #3
I second Mogens' advice.

While it is annoying to have to search the Hashtable twice, once to
check and once to remove the item, I think that this way of writing the
code will be easier to understand for other programmers. Besides, the
object not being in the Hashtable isn't really "exceptional," is it?
It's something you expect to happen regularly, so using an exception
seems a hack to me.

Trust us. :-) You gain far more speed by thinking hard about whether a
Hashtable is the right thing to use in a given situation than you do by
making little code tweaks like this one. Once you have a working
program, run it through a profiler and see where the speed problems
lie, and fix them where you find them.

Nov 1 '05 #4
Thanks for the tips, guys. I won't concern myself with trivial
optimizations like this unless I see that there's a performance bottleneck.

Jules
Nov 2 '05 #5
Jules-

i am confused at what you're doing here.

According to everything in my experience (including reading reading the
docs), Hashtable.Remove only throws an exception if the argument is null, the
table is read-only, or the table has a fixed size.

A Simple Element-Not-Found does NOT throw an exception.

Just Remove away!

now... if you were trying to properly catch all exceptions, then you should
have also looked for ArgumentNullException as well as NotSupportedException,
but that's immaterial to the examples you've presented.

No performance penalty at all =)
"Jules Winfield" wrote:
I'm often in a situation where I have a Hashtable full of objects. I'm
then presented with an object and *if* that object exists in the Hashtable,
I need to remove it from the table. I therefore have a lot of code that
looks like this:

if(ht.Contains(obj)){
ht.Remove(obj);
}

It strikes me that this code is somewhat inefficient because the
Hasthtable has to be searched *twice* : once for the Contains() call and
once for the Remove() call. So I thought maybe I should approach the
situation this way:

try{
ht.Remove(obj);
}
catch(Exception){}

Now I'm only searching the Hashtable once... but is the overhead of
throwing the exception cancelling out any benefit that I achieved by not
calling Contains()? To answer this question, you probably need to know how
frequently 'obj' is actually found in the Hashtable. For the sake of
argument, let's say 50%.

Thanks,

Jules

Nov 2 '05 #6
> A Simple Element-Not-Found does NOT throw an exception.

Ha! You're right!

I've been calling Contains() before removing since the tech preview of the
original .NET back in like 2000 or 2001 or so. I've been doing it because I
read in a tutorial that you were supposed to do this. Either the tutorial
was completely wrong or the beta version of .NET that I was using back then
actually did throw an exception when Remove() was called with an keythat
doesn't exist in the Hashtable. It's funny how a bad habit learned back in
2001 stuck with me all of these years.

Despite the moot point re:Remove(), a similar issue caught my attention
recently with the IDictionary<T> Item (that is, [] indexer) property. It
throws an exception when the key isn't found, unlike it's non-generic
counterpart which simply returns null. It looks like Microsoft addressed the
issue with a new method called TryGetValue(), which acts a lot like the []
indexer but won't throw an exception when the key isn't found.

Jules
Nov 2 '05 #7

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

Similar topics

1
by: Chandu | last post by:
Is there a way to optimize the use of Hashtable in java in terms of Memory and lookups what exactly are collisions in a hastable and how does it affect performance. Any help would be greatly...
2
by: William Stacey [MVP] | last post by:
I am doing a dns zone type of project which has an inverted tree like you all know. test.com. (top node. value contains arraylist of all test.com records) www.test.com. (node. value contains...
2
by: MFRASER | last post by:
How do I go about looping through a hash table and removing items. I know how do this in a collectionbase, but can't iterate through the hash table with out getting an error. Here is my sample...
4
by: Anders Borum | last post by:
Hello! I'm am currently working on making a central cache component threadsafe, and was looking at the synchronized implementation of the Hashtable. I was wondering why you'd really want to...
8
by: SenthilVel | last post by:
how to get the corresponding values for a given Key in hashtable ??
7
by: Kalyani | last post by:
Hi, I have a web service method which needs to return a hashtable.But it gives errror as, The type System.Collections.Hashtable is not supported because it implements IDictionary. Is there...
3
by: Jules Winfield | last post by:
I'm often in a situation where I have a Hashtable full of objects. I'm then presented with an object and *if* that object exists in the Hashtable, I need to remove it from the table. I therefore...
10
by: pamelafluente | last post by:
Hi I have a sorted list with several thousands items. In my case, but this is not important, objects are stored only in Keys, Values are all Nothing. Several of the stored objects (might be a...
4
by: Mark S. | last post by:
Much to my surprised the code below compiled and ran. I just don't know enough about threading to know for sure if this is too good to be true. I'm attempting to isolate the Hashtable lock to...
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:
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...

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.