哪个运行得更快:对每个要写入的字符串使用 OutputStreamWriter.write(),或者使用 StringBuilder 创建一个大字符串,然后使用 write() 一次?请解释原因。
这里多次使用 write():
writer.write("Registered Players:\n");
while (it.hasNext()) {
int playerID = (Integer) it.next();
Player player = playerRegistry.get(playerID);
writer.write(playerID+": "+player.getPlayerName()+"\n");
}
这是StringBuilder:
builder.append("Registered Players:\n");
while (it.hasNext()) {
int playerID = (Integer) it.next();
Player player = playerRegistry.get(playerID);
builder.append(playerID+": "+player.getPlayerName()+"\n");
}
writer.write(builder.toString());