量測操作時間
字串串接是常見操作,若實作不佳,常會成為效能瓶頸。在這個練習中,你將量測使用 + 運算子來串接字串所需的時間。
本練習屬於課程
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());
}
}