是否有“最快的方式”?用Java构建字符串? [英] Is there a "fastest way" to construct Strings in Java?

查看:103
本文介绍了是否有“最快的方式”?用Java构建字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常用以下方式在Java中创建一个String:

I normally create a String in Java the following way:

String foo = "123456";

但是,我的讲师坚持要求我使用格式方法形成一个字符串,如下所示:

However, My lecturer has insisted to me that forming a String using the format method, as so:

String foo = String.format("%s", 123456);

快得多。

此外,他说使用StringBuilder类的速度更快。

Also, he says that using the StringBuilder class is even faster.


StringBuilder sb = new StringBuilder();
String foo = sb.append(String.format("%s", 123456)).toString();



创建字符串的方法最快,如果有的话

它们不能100%准确,因为我可能不完全记得它们。

推荐答案

如果只有一个字符串,那么:

If there is only one string then:

String foo = "123456";

最快。您会注意到 String.format 行中声明了%s%,所以我不知道看看讲师怎么可能认为这更快。另外,你有一个方法调用。

Is fastest. You'll notice that the String.format line has "%s%" declared in it, so I don't see how the lecturer could possibly think that was faster. Plus you've got a method call on top of it.

但是,如果你正在构建一个字符串,例如在for循环中,那么你我想要使​​用StringBuilder。如果您只是使用 + = ,那么每次 + = 调用code>行。 StringBuilder更快,因为它每次调用追加时都会保留一个缓冲区并附加到它。

However, if you're building a string over time, such as in a for-loop, then you'll want to use a StringBuilder. If you were to just use += then you're building a brand new string every time the += line is called. StringBuilder is much faster since it holds a buffer and appends to that every time you call append.

这篇关于是否有“最快的方式”?用Java构建字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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