-2

Just started to learn Scala :) The question right away: Why printing to stdout is so slow?

$ time scala -e 'val s = "foobarjoe!"; for (i <- 1 to 10000000) println(s)' > /dev/null

real    0m22.522s
user    0m14.252s
sys     0m8.508s

$ scala -version
Scala code runner version 2.11.4 -- Copyright 2002-2013, LAMP/EPFL

The same code in Perl as an example:

$ time perl -le '$s = "foobarjoe!"; for (1..10000000) { print($s) }' > /dev/null

real    0m1.276s
user    0m1.266s
sys     0m0.010s
  • 2
    Probably because it has to compile, initialize the JVM multiple times, etc. – corazza Dec 23 '14 at 21:40
  • anyway - pretty sure results will be same for Java itself, so it's not a question about Scala (even regardless that Scala compiles very slooow in comparison with Java) – dk14 Dec 23 '14 at 21:45
  • 1
    2jco: Less a second for it: $ time scala -e 'println("Hi, there")' Hi, there real 0m0.765s user 0m0.537s sys 0m0.089s – aleksey.ischenko Dec 23 '14 at 21:45
  • as i said it's a Java question (and not related to Scala) - for example see http://stackoverflow.com/questions/4437715/why-is-system-out-println-so-slow – dk14 Dec 23 '14 at 21:50

1 Answers1

1

This link answers the question: http://www.rgagnon.com/javadetails/java-0603.html

If your program is doing a lot printing to the console using System.out.println() then it is possible to get a good performance boost by using an alternative to do the console output.

By default, System.out.print() is only line-buffered and does a lot work related to Unicode handling. Because of its small buffer size, System.out.println() is not well suited to handle many repetitive outputs in a batch mode. Each line is flushed right away. If your output is mainly ASCII-based then by removing the Unicode-related activities, the overall execution time will be better.

It now remains to translate the solution from Java to Scala :)

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
     FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);
Community
  • 1
  • 1