简体   繁体   中英

System.out.println vs PrintWriter

Is there a difference in using these two? When would you use one over the other?

System.out.println(result);

versus

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

The main difference is that System.out is a PrintStream and the other one is a PrintWriter . Essentially, PrintStream should be used to write a stream of bytes , while PrintWriter should be used to write a stream of characters (and thus it deals with character encodings and such).

For most use cases, there is no difference.

System.out is instance of PrintStream

So your question narrows down to PrintStream vs PrintWriter

  • All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. (Syso writes out directly to system output/console)

  • The PrintWriter class should be used in situations that require writing characters rather than bytes.

I recommend using PrintWriter if you have to print more than 10^3 lines in one go. 性能比较高达 10^5 性能比较高达 10^7

I got this by running these snippets 3 times each for n=10^1 to 10^7 and then taking mean of there execution time.

class Sprint{
    public static void main(String[] args) {
        int n=10000000;
        for(int i=0;i<n;i++){
            System.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();
    }
}

Yes, there is a slight difference. out.println() is short and is used in JSP while PrintWriter is used in servlets. out.println() is also derived from PrintWriter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM