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

toString() and typecast to String

 
Roopa Bharani
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a problem in which I can either use the toString() method to get the String version of an object or typecast it to String. But i want to know which is the more efficient way of doing this??
In terms of memory and cpu utilization which approach would be better?

Thanks,
Roopa.
 
Anubhav Anand
Ranch Hand
Posts: 341
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roopa Bharani,
Welcome to JavaRanch.

The cast version : (String) myObject is faster than the myObject.toString()

Actually, as *I* know that myObject.toString() is transformed to
((String) myObject.toString()). So, this in turn requires an extra call to toString() thus, it's a bit slower.

Well, in a normal application you would hardly find the difference as the difference actually accounts when there are very huge say millions of such operrations.

Another point to consider when you use either ways is that if the object you are working on is null then toString() will throw exception. Moreover, you have to be very careful that the object can actually be reffred as String.

If you are using collections, Maps etc. then it is always better to use Generics(JDK5.0).

Hope that helps. Good Luck..!!
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Er, what?! Casting and toString() are not alternatives to one another.

Casting is something you do to an object reference. If you have a reference of type java.lang.Object, but the object referred-to is really a String, you can cast it to String. However, if the object referred-to is not a String, this will not make it into a String.

The toString() method is entirely different. For a start, a method is something that an object has, not an object reference has. All objects have a toString() method, which will return a String that somehow represents the object. The version of toString() in java.lang.Object is only suitable for debugging purposes, but some objects override toString() to give something more readable.

If you're still confused about this sort of thing, then it's far too early in your Java learning curve to be worrying about what's faster than what.
[ March 18, 2008: Message edited by: Peter Chase ]
 
steve souza
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As previous posters have mentioned this is more of a design question than a performance question. And rarely if ever will this design choice impact the overall performance of your application.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic