javasystem.out

How can I disable System.out for speed in Java


I'm writing a program in Java that simulates gravity, and in it I have a bunch of log statements (to System.out). My program is running really slowly, and I think the logging might be part of the reason. Is there any way to disable System.out, so that my program doesn't slow down when printing, or do I have to manually go through and comment/uncomment each one to enable/disable debug statements?


Solution

  • I agree with others that a proper logger should be used. However that is not possible in every case. The following code disables out and is fast as OP asked:

    System.setOut(new java.io.PrintStream(new java.io.OutputStream() {
        @Override public void write(int b) {}
    }) {
        @Override public void flush() {}
        @Override public void close() {}
        @Override public void write(int b) {}
        @Override public void write(byte[] b) {}
        @Override public void write(byte[] buf, int off, int len) {}
        @Override public void print(boolean b) {}
        @Override public void print(char c) {}
        @Override public void print(int i) {}
        @Override public void print(long l) {}
        @Override public void print(float f) {}
        @Override public void print(double d) {}
        @Override public void print(char[] s) {}
        @Override public void print(String s) {}
        @Override public void print(Object obj) {}
        @Override public void println() {}
        @Override public void println(boolean x) {}
        @Override public void println(char x) {}
        @Override public void println(int x) {}
        @Override public void println(long x) {}
        @Override public void println(float x) {}
        @Override public void println(double x) {}
        @Override public void println(char[] x) {}
        @Override public void println(String x) {}
        @Override public void println(Object x) {}
        @Override public java.io.PrintStream printf(String format, Object... args) { return this; }
        @Override public java.io.PrintStream printf(java.util.Locale l, String format, Object... args) { return this; }
        @Override public java.io.PrintStream format(String format, Object... args) { return this; }
        @Override public java.io.PrintStream format(java.util.Locale l, String format, Object... args) { return this; }
        @Override public java.io.PrintStream append(CharSequence csq) { return this; }
        @Override public java.io.PrintStream append(CharSequence csq, int start, int end) { return this; }
        @Override public java.io.PrintStream append(char c) { return this; }
    });
    

    My sample measurements were:

    So it is faster than other answers here, but can't beat non-existent code (commenting out System.outs or wrapping in if (DEBUG)) as varargs allocates arrays and boxes primitives or StringBuilder (+ too) still executes.