简体   繁体   English

何时在 Java 中使用 String#concat() 方法?

[英]When to use String#concat() method in Java?

I've been through different topics about String concatenation performance.我已经了解了有关字符串连接性能的不同主题。 Almost answer recommend using StringBuilder or StringBuffer to reduce overhead cost (or + operator if concatenation statement outside the loop).几乎答案建议使用StringBuilderStringBuffer来减少开销成本(如果连接语句在循环外,则为+运算符)。 It's pretty clear, but I still wonder why Java has String format() and concat() method although it's ineffective.很清楚,但我仍然想知道为什么 Java 有 String format()concat()方法,尽管它无效。 Performance test here: link .性能测试在这里:链接 Someone mentioned String format() may be useful for Localization purpose (I don't understand much, howsoever I already have a keyword to search later), but what's the purpose of the remaining one?有人提到 String format()可能对Localization目的有用(我不太明白,但是我已经有一个关键字可以稍后搜索),但剩下的一个目的是什么? Does it only useful for compatibility backward?它仅对向后兼容有用吗?

String#concat and + exist to provide a minimalistic set of operations on the type String. String#concat+存在是为了在类型 String 上提供一组简约的操作

They are not efficient if used multiple times.如果多次使用,它们效率不高。

But they have their own right as type operations "xxx" + "yyy" you do not want to specify using a StringBuilder.但是他们有自己的权利,因为您不想使用 StringBuilder 指定类型操作"xxx" + "yyy" (Furthermore there it is a compile time concatenation.) (此外,它是一个编译时串联。)

StringBuffer is a mistake IMHO. StringBuffer是一个错误恕我直言。 It is slower that the newer StringBuilder as it is synchronized, but one would rarely add something rom two threads (unordered).较新的StringBuilder较慢,因为它是同步的,但很少会在两个线程(无序)中添加一些东西。

String::concat may be a method reference useful for stream reduction or such. String::concat可能是对流减少等有用的方法引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM