String.valueOf(someVar) vs ("" + someVar) [英] String.valueOf(someVar) vs ("" + someVar)

查看:31
本文介绍了String.valueOf(someVar) vs ("" + someVar)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道两种方法的区别.我现在正在处理一些旧代码,它们通过与空字符串 ""primitive 值设置为 String 值代码>.

I want to know the difference in two approaches. There are some old codes on which I'm working now, where they are setting primitive values to a String value by concatenating with an empty String "".

obj.setSomeString("" + primitiveVariable);

但是在这个链接中空 Java 字符串的大小它说如果您为每个实例创建一个单独的空字符串,那么显然这将占用更多内存.

所以我想到了在String 类中使用valueOf 方法.我检查了文档 String.valueOf() 它说 如果参数为空,则字符串等于空";否则返回 obj.toString() 的值.

So I thought of using valueOf method in String class. I checked the documentation String.valueOf() it says If the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

哪一个更好

  1. obj.setSomeString("" + originalVariable);
  2. obj.setSomeString(String.valueOf(primitiveVariable));

上述过程是在List迭代中完成的,该迭代的大小超过600,预计未来还会增加.

The above described process of is done within a List iteration which is having a size of more than 600, and is expected to increase in future.

推荐答案

当您执行 "" 时,不会创建对象.它将创建一个字符串文字.有区别(实际上如何使用"?)初始化字符串.

When you do "" that is not going to create an Object. It is going to create a String literal. There is a differenc(How can a string be initialized using " "?) actually.

回到你的实际问题,

来自字符串连接文档

Java 语言为字符串连接运算符 ( + ) 以及将其他对象转换为字符串提供了特殊支持.字符串连接是通过 StringBuilder(或 StringBuffer)类及其 append 方法实现的.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

因此,您正在创建 StringBuilder 对象,然后生成另一个 String 对象.

So unnecissarly you are creating StringBuilder object and then that is giving another String object.

然而 valueOf 直接给你一个 String 对象.去吧.

However valueOf directly give you a String object. Just go for it.

除了性能之外,再考虑一下.为什么要连接空字符串,而实际上您想将 int 转换为 String :)

Besides the performance, just think generally. Why you concatenating with empty string, when actually you want to convert the int to String :)

这篇关于String.valueOf(someVar) vs ("" + someVar)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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