Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.valueOf(i) vs "" + i or i + ""

I usually use "" + i for convenient. But compare about perfomance myself, I thought String.valueOf(i) will be faster. Is it right? Which one should I use?

like image 480
Luke Vo Avatar asked Feb 23 '23 05:02

Luke Vo


2 Answers

I don't think you will be able to see any measurable difference. This seems to be what is usually referred to as micro (premature?) optimizations and are seldom a good idea.

Choose the method you and your fellow colleagues find easiest to read.

like image 156
aioobe Avatar answered Mar 04 '23 14:03

aioobe


Choose what reads best. Then, profile your application before optimizing anything.

Always profile first (for instance with VisualVM since you're coding in Java).

There are many resources on profiling and optimization. The latest good read I came across is this Step by Step Optimisation by Tony Albrecht.

And if performance really becomes critical, consider switching to StringBuilder.

EDIT:

Well there is no straight answer to your question imho. Micro-benchmarking the performance of String.valueOf(i) against i + "" has little value. The real answer comes from benchmarking your application: its very own complexity and memory access pattern decides it all.

Those are not my ideas but I'm buying them: stop programming like it's 1975, big O notation needs an update.

like image 21
Gregory Pakosz Avatar answered Mar 04 '23 15:03

Gregory Pakosz