開始使用免費開始

量測操作時間

字串串接是常見操作,若實作不佳,常會成為效能瓶頸。在這個練習中,你將量測使用 + 運算子來串接字串所需的時間。

本練習屬於課程

Java 程式碼最佳化

檢視課程

練習說明

  • 在操作前後分別紀錄開始時間與結束時間。
  • 使用 startTimeendTime 計算此操作的總耗時。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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());
    }
}
編輯並執行程式碼