Is HashMap slow?

D

Daniel

While building business classes, I store the properties/db fields in a
HashMap. So to retrieve the value I use:

String value = (String)fields.get(fieldName);

To save, I pass the HashMap on to a generic Database table class. This
class uses an Iterator to generate the sql statements;

for (Iterator e = fields.keySet().iterator(); e.hasNext() ;) {
..
String key = (String)e.next();
sql += key + " = " + (String)fields.get(key);
..
}


So my question is if the HashMap is too slow for this? If so, is there
a better way to do the same thing?
 
M

Matt Humphrey

Daniel said:
While building business classes, I store the properties/db fields in a
HashMap. So to retrieve the value I use:

String value = (String)fields.get(fieldName);

To save, I pass the HashMap on to a generic Database table class. This
class uses an Iterator to generate the sql statements;

for (Iterator e = fields.keySet().iterator(); e.hasNext() ;) {
..
String key = (String)e.next();
sql += key + " = " + (String)fields.get(key);
..
}


So my question is if the HashMap is too slow for this? If so, is there
a better way to do the same thing?

It's very unlikely that HashMap is too slow. If you're concerned about
speed, run a profiler to actually find out where your bottleneck is rather
than trying shotgun optimizations. Using += for String concatenation can
create many short-lived objects, however. The preferred technique is:

StringBuffer sqlBuffer = new StringBuffer (sql);

sqlBuffer.append (key);
sqlBuffer.append ("=");
sqlBufer.append ((String)fields.get(key));


sql = sqlBuffer.toString ();

etc.

Matt Humphrey (e-mail address removed) http://www.iviz.com/
 
F

fake_healer

Thanks for your reply.

It's not slow, but I figured it being better to ask at a state where I
can still change things.

I suspected that the StringBuffer would be a better choice. But since
the strings are so short, I thought it would make much difference.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top