将int转换为String的最有效方法是什么? [英] What is the most efficient way to convert an int to a String?

查看:107
本文介绍了将int转换为String的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

int someValue = 42;

现在,我要将int值转换为String.哪种方法更有效?

Now I want to convert that int value to a String. Which way is more efficient?

// One
String stringValue = Integer.toString(someValue);

// Two
String stringValue = String.valueOf(someValue);

// Three
String stringValue = someValue + "";

我只是好奇是否存在真正的差异,或者一个比另一个更好?

I am just curious if there is any real difference or one is better than the other?

推荐答案

测试了10m分配的数字10

tested it for 10m assignments of the number 10

One:
real    0m5.610s
user    0m5.098s
sys     0m0.220s

Two:
real    0m6.216s
user    0m5.700s
sys     0m0.213s

Three:
real    0m12.986s
user    0m11.767s
sys     0m0.489s

似乎有人赢了

JVM是Mac OS X 10.5下的标准'/usr/bin/java'

JVM is standard '/usr/bin/java' under Mac OS X 10.5


java version "1.5.0_16"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-284)
Java HotSpot(TM) Client VM (build 1.5.0_16-133, mixed mode, sharing)

更多修改:

根据要求输入代码

public class One {
    public static void main(String[] args) {
        int someValue = 10;
        for (int i = 0; i < 10000000; i++) {
            String stringValue = Integer.toString(someValue);
        }
    }
}

情况2和3类似地
使用

case 2 and 3 similarly
run using

javac *.java; time java One; time java Two; time java Three

这篇关于将int转换为String的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆