HbnKing
HbnKing

Reputation: 1882

Performance cost of type conversion in Java ,How to choses?

In many cases we need to convert the type of data, but there are more ways to convert between Number ​​and String. How to choses ? Do they have different performance?
Example :
convert int to String

int i=5;
String s1=String.valueOf(i);
String s2=i+"";
String s3=Integer.toString(i);
etc..

convert String to int

String sint = "9999" ;
int integer = Integer.valueOf(sint);
int integer = Integer.parseInt(sint);
int integer = Ints.tryParse(sint);

int integer = NumberUtils.createInteger(sint);
int integer = NumberUtils.toInt(sint);
int integer = NumberUtils.createInteger(sint);
etc..

Upvotes: 1

Views: 894

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201447

Prefer the version that returns a primitive.

int integer = Integer.valueOf(sint); // unboxes Integer
int integer = Integer.parseInt(sint); // returns int

As for converting int to String, those perform the same (one calls the other, and the JIT optimizes away any difference there).

Upvotes: 3

Related Questions