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.
Diese Übung ist Teil des Kurses
Optimizing Code in Java
Anleitung zur Übung
- Record the start time and the end time before and after our operation.
- Calculate the total duration for our operation using
startTimeandendTime.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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());
}
}