Why using System.out.printf() instead of System.out.println() causes Time Limit Exceeded?

Viewed 115

Recently I was solving a question on codeforces. On coding its solution at the end I had to print the values from a 2 dimensional array for which I used,

for (int p = 0; p < m; p++) {
    if (positions[edges[p][0]-1] < positions[edges[p][1]-1]) {
        System.out.printf("%d %d\n", edges[p][0], edges[p][1]);
    } else {
        System.out.printf("%d %d\n", edges[p][1], edges[p][0]);
    }
}

Using the above approach caused a Time Limit Exceed on a test case. While I replaced the above code to the one like the following, it worked.

for (int p = 0; p < m; p++) {
    if (positions[edges[p][0]-1] < positions[edges[p][1]-1]) {
        System.out.println((edges[p][0]) + " " + (edges[p][1]));
    } else {
        System.out.println((edges[p][1]) + " " + (edges[p][0]));
    }
}

What could have caused this?

My submission for reproducing here

1 Answers

I created a simple test (of course it's not a benchmark, but it can simply give some conclusions):

public static void main(String[] args) {
    long beforePrintln = System.nanoTime();
    int a = 1;
    int b = 2;
    for (int i = 0; i < 1000000; i++) {
        System.out.println(a + " string " + b);
    }
    long beforePrintf = System.nanoTime();
    for (int i = 0; i < 1000000; i++) {
        System.out.printf("%d string %d\n", a, b);
    }
    long after = System.nanoTime();
    System.out.println();
    System.out.println(beforePrintf - beforePrintln);
    System.out.println(after - beforePrintf);
}

and the results are (I run it multiple times and result are always almost the same):

4796301400
9976818400

It seems that printf (with string formating) is 2 times slower than println with string concatenation. I think printf is slower because it's much more powerfull in formatting output than simple println which just prints given line.

Related