(String) or .toString()?

I have a method with an Object o parameter.

In this method, I exactly know there is a String in "o" which is not null. There is no need to check, or do something else. I have to treat it exactly like a String object.

Just curious - what is cheaper - cast it to String, or use Object.toString()? Or is it same by time-/cpu-/mem- price?

Update: The method accepts Object because it's the implementation of an interface. There is no way to change the parameter type.

And it can't be null at all. I just wanted to say that I do not need to check it for null or emptyness. In my case, there is always a nonempty string.


Solution 1:

casting to a String is cheaper since that doesn't require an external function call, just internal type checking.

Solution 2:

I would use a cast. That validates your "knowledge" that it's a string. If for whatever reason you end up with a bug and someone passes in something other than a string, I think it would be better to throw an exception (which a cast will do) than continue to execute with flawed data.

Solution 3:

According to Silly performance musings: x.toString() vs (String)x

In thend end, results are surprisingly clear: it is at least twice as fast to cast Object to String than to call Object.toString()

Solution 4:

If you know the Object o is a String, I'd say just cast it to a String and enforce it that way. Calling toString() on an object that you know for sure is a String might just add confusion.

If Object o might be anything other than a String, you'll need to call toString().

Solution 5:

I wouldn't be too concerned by the performance, if this operation is done even just a few thousand times a second - there's no tangible difference.

I would, however, be concerned of "knowing" the input. You have a method that accepts an Object and you should treat it as such, i.e. you shouldn't know anything about the parameter, other than it adheres to the Object interface, which happens to have a toString() method. In this case, I would strongly suggest using that method instead of just assuming anything.

OTOH, if the input is always either String or null, just change the method to accept Strings, and check explicitly for nulls (which you should do anyways whenever dealing with non-primitives...)