测量操作耗时
字符串拼接是常见操作,如果实现不当,可能成为性能瓶颈。在本练习中,您将测量使用 + 运算符拼接字符串所需的时间。
本练习是课程的一部分
Java 代码优化
练习说明
- 在操作前后分别记录开始时间和结束时间。
- 使用
startTime和endTime计算该操作的总耗时。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class Main {
public static void main(String[] args) {
// Get the start time
long startTime = System.____();
String result = "";
for (int i = 0; i < 10000; i++) {
// Add the current number to the result string
result += i;
}
// Get the end time
long endTime = ____.nanoTime();
// Calculate the duration
long durationInNanos = ____;
double durationInMillis = durationInNanos / 1_000_000.0;
System.out.println("String concatenation took: " + durationInMillis + " ms");
System.out.println("Final string length: " + result.length());
}
}