0

What is the difference between these two codes: (the object is any random object)

Object object = anything;
String str = object+"";

and

Object object = anything;
String str = object.toString();

They both return the same String.

How do they performance? Which one is better?

2 Answers 2

4

If you decompile these examples using javap -c you will see that in first case

  • StringBuilder will be created
  • and it will append(Object obj)
  • which internally will invoke append(String.valueOf(obj));
  • which first will check for null reference.

So main difference in result of null

Object o = null;
System.out.println(o + ""); // result "null"
System.out.println(o.toString()); // throws NPE

If your data can't be null or you want to throw NPE you should use toString() for better performance.

If your data can be null and in this case result string should also be "null" String.valueOf(object) will give you better performance than object+"".

Sign up to request clarification or add additional context in comments.

Comments

2

The first one is equivalent to:

Object object = anything;
String str = new StringBuilder().append(object).toString();

whereas the second is just a plain toString() call. The performance difference is likely to be negligible, but the second will almost certainly be marginally faster because it doesn't use an unnecessary StringBuilder. Generally, prefer the second approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.