Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: What's the reason behind System.out.println() being that slow?

For small logical programs that can be done in a text editor, for tracing I use the classic System.out.println().

I guess you all know how frustrating it is to use that in a block of high number of iterations. Why is it so slow? What's the reason behind it?

like image 361
Sajal Dutta Avatar asked Jun 04 '09 11:06

Sajal Dutta


3 Answers

This has nothing whatsoever to do with the JVM. Printing text to screen simply involves a lot of work for the OS in drawing the letters and especially scrolling. If you redirect System.out to a file, it will be much faster.

like image 152
Michael Borgwardt Avatar answered Nov 16 '22 02:11

Michael Borgwardt


This is very OS-dependent. For example, in Windows, writing to the console is a blocking operation, and it's also slow, and so writing lots of data to the console slows down (or blocks) your application. In unix-type OSes, writing to the console is buffered, so your app can continue unblocked, and the console will catch up as it can.

like image 29
skaffman Avatar answered Nov 16 '22 03:11

skaffman


Ya, there is a huge amount of overhead in writing to the console. Far greater than that required to write to a file or a socket. Also if there are a large number of threads they are all contending on the same lock. I would recommend using something other that System.out.println to trace.

like image 28
ng. Avatar answered Nov 16 '22 04:11

ng.