Domanda

Does Java run any code for System.out.println(...) when I run the program in a console-less GUI? (where I don't redirect the program output to anywhere)

In fact I'd like to know if System.out.println(...) can affect the program performance when it is run by clicking the jar file.

Consider that I print thousands of lines per minute.

È stato utile?

Soluzione

The way Java deals with calls, there probably will be significant impact if you println something that's not a simple string.

For example,

System.out.println("Iteration " + i);

creates a StringBuilder, converts an int and copies a bunch of characters before it can even decide that there is nothing behind System.out.

Altri suggerimenti

Let me put it this way.

If you were to execute you program from another program, then you would be able to read the stdout of your program, so yes, there is always something sent to stdout even if nothing is "listening"

From experience, we found there was an improvement in performance (under windows), if redirected the stdout and stderr thur a null stream (which consumed the streams), but we were dealing with a lot of output not just from our program but also the RMI server we were communicating with

you are writing to standard out, if there is no listener for that stream then no worries.

theoretically yes, It can affect performance since it is in fact a method call and method calls use minute amounts of processing power. However on a modern computer It will have no affect to general performance, In fact most modern programs/games use println's to debug their program even in real releases. I would leave them there if they are a necessity.

See the docs on Out here:

http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#out

Even if there isn't an listener on the out stream you're still going to have overhead from the calls. Your performance effects will depend largely on the amount of this your doing. If there is a listener, then you're going to see much higher performance impact.

TLDR: The compiler isn't going to remove the system.out.println call, so you'll see some marginal performance hit.

By looking here it looks like that multiple method calls are done inside println before any check on whether or not someone is listening the streaming.

THEN:

For this purpose I'd prefer to create a Debug class with a print method as I'm totally sure that it doesn't affect performance:

public class Debug {
    public static boolean debug = true;
    public static int debLev = 5;

    public static void print(String stringa){
        if(debug)
            System.out.println(stringa);
    }

    public static void print(String stringa, int level){
        if(debug && level >= debLev){
            System.out.println(stringa);
        }
    }
}

In this way you can disable printing and also you can filter debug printing by severity.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top