最佳实践是将Double转换为String。

huangapple go评论71阅读模式
英文:

Best practice to convert a Double to a String

问题

我目前正在使用

Double a = 0.00;

for(condition)
    //做一些事情

String result = "" + a;

相比于我现在的写法,使用

String result = a.toString();

会带来实质性的好处吗?这只是帮助编译器,还是这两种方法之间有区别?

英文:

I am currently using

Double a = 0.00;

for(condition)
    //Do things

String result = "" + a;

Would using

String result = a.toString();

Provide any real benefit compared to what I have now. Does this just help the compiler or are there any differences between the two methods?

答案1

得分: 2

第一个版本 - 在内部,String result = "" + aString result = "" + a.toString(); 是相同的。每当字符串与对象进行连接时,将调用 toString 方法。

在这里,什么是最佳实践?哪个看起来更好呢?我可能会选择第一个版本。

如果你关心它们的性能 - String result = a.toString(); 从理论上讲会更快,因为你不需要创建/获取一个空字符串来创建一个新字符串。然而,与 Java 中的许多事情一样,像这样的事情很可能会被 JIT 编译器优化,所以我不会过多担心它。即使没有被优化,你也不应该过早地担心优化 - 如果你的代码运行缓慢,通常有比这个问题更大的问题。

英文:

The first version - String result = "" + a under the hood is the same as String result = "" + a.toString();. Whenever there is a concatenation of String + Object the toString method is called.

What is the best practice here? What looks better for you. I'd probably go with the first version.

If you're concerned about the performance of both - String result = a.toString(); on paper will be faster because you don't need to create / get an empty String just to create a new one. However, as with many things in Java, something like that most likely gets optimized by JIT compiler anyway so I wouldn't worry about it too much. Even if it doesn't you shouldn't worry about optimization prematurely - if your code runs slowly then usually there is something else wrong with it that is much bigger than that.

答案2

得分: 1

我认为第二个选项更好,因为字符串的连接消耗更多的内存。由于在第一种方式中,字符串是不可变对象,所以您的内存将被浪费用于存储一个Double对象 + 两个字符串对象。

但是在第二个选项中,它只会创建一个新的字符串对象。因此在您的内存中只会有一个Double对象 + 一个字符串对象。

英文:

I think second option is better because concatenation of strings cost much more memory.Since Strings are immutable objects in the first way your memory is wasting for store a Double object + two String Objects .

But in the second option it only create one new String object only .So in your memory there will only be one Double object + one String Object.

huangapple
  • 本文由 发表于 2020年7月27日 18:42:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63113644.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定