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
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.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
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?
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.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus