在Java中连接字符串是否总是导致在内存中创建新字符串?
2022-09-01 18:30:29
我有一根长绳子,不适合屏幕的宽度。例如。
String longString = "This string is very long. It does not fit the width of the screen. So you have to scroll horizontally to read the whole string. This is very inconvenient indeed.";
为了便于阅读,我想过这样写——
String longString = "This string is very long." +
"It does not fit the width of the screen." +
"So you have to scroll horizontally" +
"to read the whole string." +
"This is very inconvenient indeed.";
但是,我意识到第二种方法使用字符串串联,并将在内存中创建5个新字符串,这可能会导致性能下降。事实果真如此吗?或者编译器会足够聪明,弄清楚我所需要的只是一个字符串吗?我怎么能避免这样做?