Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting to Vs toString()

 
Mahesh Pinnamaneni
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

i want to know the performance of these two things.
Say: I have to take an item from the HashMap and convert to String.
ex: HashMap hm = new HashMap();
hm.put("a","aaa");
hm.put("b","ggaa");
hm.put("c","aaggga");

if i do hm.get("a"); i will get an object and which i have to convert to string.
i can do this as following ways:

String aaa = hm.get("a").toString();
or
String bbb = (String)hm.get("a");

In these above 2 ways which one is faster.

I am posting this becoz i have tons of data to convert to string from the HashMap.
Pls help me..
Thanks & Reply,
Mahesh
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it's generally dangerous to try to say what is faster, without measurement, but I'm going to try.

The casting version sounds like it would be faster than the toString() version. For casting, all that is necessary for the runtime is to check the actual class of the object. For toString(), it has to do a dynamically-despatched method call.

There is another reason to use casting, not toString(). The casting version implicitly checks your assumption that the data in the hash map is String data. Casting will fail if it is not. That's a good thing, because if you've got the wrong type of data in the map, you want to know straight away, not have to debug whatever subtle bug results from it. In contrast, you can call toString() on any Object, and it will return a String. So it will happily work on completely the wrong type of data, which is a bad thing.
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In these above 2 ways which one is faster.

I am posting this becoz i have tons of data to convert to string from the HashMap.


Well - two questions:
a) What is 'tons of data'?
b) What is the problem in writing a small test, preferably with original data and using a machine, which is similar to the one, where the program will run?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not really sure which way is faster, but frankly I doubt that it makes a significant difference. I'd go with casting for the other reason Peter already explained.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic