想象一下,您希望向游戏显示欢迎消息,但需要保持源代码中的行最大长度为80个字符。在游戏中,线条的长度并不重要。欢迎信息的一个例子是:
private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me how to create a long messages like this in a read-able fashion. Imagine there is a limit of 80 characters per line for a programmer to see. How to fix this efficiently? This is one large line in my IDEA. ");
}
这条线太长了,每行代码只有80个字符,滚动条可以看到。我之前学会了简单地做这样的事情:
private void welcomeMessage() {
System.out.println("Welcome to the game. This message should learn me" +
" how to create a long messages like this in a read-able " +
"fashion. Imagine there is a limit of 80 characters per line for" +
" a programmer to see. How to fix this efficiently? This is one " +
"large line in my IDEA. ");
}
但是我发现这个解决方案很难看,这会产生一种非常烦人的依赖。如果我只添加"Welcome to the game. This message should learn me"
一个单词,我必须更改所有其他行,因此一行后面的所有行都取决于它。
我还可以想象,只有通过这种方式让它可读才会受到惩罚。这让我想知道:
想象一下,这是一款真正的游戏,您是否只需创建一个txt文本文件并使用StringBuffer等导入它以在屏幕上显示它?或者你会如何显示更长的短信?
答案 0 :(得分:2)
编译器是否直接追加所有行,因为它们本身不依赖于其他变量,或者它是否在运行时发生? (我担心它会调用串联运算符函数('+')4次)
编译器将连接字符串。没有运行时开销。
在这个例子中,带有.append()的StringBuffer是否会更有效,因为它不会创建5个字符串,而是将它附加到StringBuilder对象?
没有
演示:
class Test {
public static String test = "a" + "b" + "c";
}
命令
javac Test.java && javap -c -v Test
产生以下输出
[...]
Constant pool:
#1 = Methodref #5.#15 // java/lang/Object."<init>":()V
#2 = String #16 // abc
#3 = Fieldref #4.#17 // Test.test:Ljava/lang/String;
[...]
Code:
stack=1, locals=0, args_size=0
0: ldc #2 // String abc
2: putstatic #3 // Field test:Ljava/lang/String;
5: return
[...]