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?
PrintWritter gives better performance, though the time difference is not quite visible in smaller programs.
But becomes quite apparent as the number of lines to be printed increases.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With