Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out.println vs PrintWriter performance comparison?

I want to print 1 million lines to stdout.

System.out.println(result);

Or

PrintWriter out = new PrintWriter(System.out);
out.println(result);
out.flush();

To get better performance(speed wise), which one should I use and why?

--Edit-- How about BufferedWriter?

like image 433
noooooooob Avatar asked Sep 20 '25 07:09

noooooooob


1 Answers

PrintWritter gives better performance, though the time difference is not quite visible in smaller programs. Performace Graph But becomes quite apparent as the number of lines to be printed increases. Performance Graph

I used the execution time of these snippets for the test. System.out.println(i)

class Sprint{
    public static void main(String[] args) {
        int n=10000000;
        for(int i=0;i<n;i++){
            System.out.println(i);
        }
    }
}

out.println(i);

import java.io.*;
class Pprint{
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        int n=10000000;
        for(int i=0;i<n;i++){
            out.println(i);
        }
        out.flush();
    }
}

I used n=10 to 10^7 and executed both of them 3 times for each n. There was a visible difference in performance after the value of n exceeds 10^3.

like image 70
Abhinav Mani Avatar answered Sep 22 '25 20:09

Abhinav Mani