Get startedGet started for free

Measuring operation time

String concatenation is a common operation that can be a performance bottleneck when not implemented efficiently. In this exercise, you'll measure how long it takes to concatenate strings using the + operator.

This exercise is part of the course

Optimizing Code in Java

View Course

Exercise instructions

  • Record the start time and the end time before and after our operation.
  • Calculate the total duration for our operation.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Get the start time
        long startTime = ____
        
        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 = ____
        
        // 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());
    }
}
Edit and Run Code