問題文
A method builds one line of text by concatenating a few thousand short pieces inside a loop. Readability is not a concern here but the time spent is. What is the best choice?
選択肢
- Collect the pieces into a list and join them at the end with the method of String that takes a separator, and that avoids creating any intermediate text at all.
- Concatenate with the plus operator, and the compiler optimizes it away while it builds each line.
- Append the pieces to one StringBuilder inside the loop and convert it to a String once after the loop has finished.
- Concatenate into a String but declare the variable as final so the compiler keeps the value in a register, so the loop avoids extra garbage.