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.
Este ejercicio forma parte del curso
Optimizing Code in Java
Instrucciones del ejercicio
- Record the start time and the end time before and after our operation.
- Calculate the total duration for our operation using
startTimeandendTime.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
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());
}
}