A few days ago I realized that I had never done any experimentation with measuring the time it takes for a program to run. I decided for fun just to test out some random lines of code for the heck of it using the System.currentTimeMillis() method. I decided to try out something simple, such as merely continuously reassigning a variable. So, I ran the following code:
public class Timer{
public static void main(String[] args) {
String s = null;
final long startTime = System.currentTimeMillis(); // Start the timer
for (int i = 1; i <= 999999999; i++) {
s = i + "Hello"; // This takes around 36 seconds!
}
System.out.println(s);
final long endTime = System.currentTimeMillis(); // End the timer
System.out.println("Total execution time: " + (endTime - startTime)); // Report total time elapsed
}
}
I was amazed to see that just continuously reassigning a String variable would take so long. I know the number up to which I'm iterating is quite huge in and of itself, but when I ran other code that still involved the for-loop up to that huge number, the time it took for the program to run was significantly lower. For example:
import java.util.ArrayList;
public class TimerArrayList {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
final long startTime = System.currentTimeMillis(); // Start the timer
// Adding elements to an ArrayList is generally quick (around 4 seconds)
for (int i = 1; i <= 999999999; i++) {
list.add(i);
if (list.size() == 50000)
list.clear(); // To prevent OutOfMemoryError
}
final long endTime = System.currentTimeMillis(); // End the timer
System.out.println("Total execution time: " + (endTime - startTime)); // Report total time elapsed
}
}
Adding elements to the ArrayList took only about 4 seconds. Even faster yet was merely counting up. For instance, this code took on average 1.5 milliseconds to run:
public class TimerCounting{
public static void main(String[] args) {
final long startTime = System.currentTimeMillis(); // Start the timer
// Just counting up is super quick (around 1 millisecond)
int counter = 0;
for (int i = 1; i <= 999999999; i++) {
counter = i;
}
final long endTime = System.currentTimeMillis(); // End the timer
System.out.println("Total execution time: " + (endTime - startTime)); // Report total time elapsed
}
}
So, my question is: why does it take so long just to reassign a String variable?