Saturday, May 25, 2019

java - Why is System.out.println so slow?



Is this something common to all programming languages? Doing multiple print followed by a println seems faster but moving everything to a string and just printing that seems fastest. Why?



EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!



EX:



package sieveoferatosthenes;
public class Main {

public static void main(String[] args) {
int upTo = 10000000;
boolean primes[] = new boolean[upTo];
for( int b = 0; b < upTo; b++ ){
primes[b] = true;
}
primes[0] = false;
primes[1] = false;

int testing = 1;


while( testing <= Math.sqrt(upTo)){
testing ++;
int testingWith = testing;
if( primes[testing] ){
while( testingWith < upTo ){
testingWith = testingWith + testing;
if ( testingWith >= upTo){
}
else{

primes[testingWith] = false;
}

}
}
}
for( int b = 2; b < upTo; b++){
if( primes[b] ){
System.out.println( b );
}

}
}
}

Answer



println is not slow, it's the underlying PrintStream that is connected with the console, provided by the hosting operating system.



You can check it yourself: compare dumping a large text file to the console with piping the same textfile into another file:



cat largeTextFile.txt

cat largeTextFile.txt > temp.txt


Reading and writing are similiar and proportional to the size of the file (O(n)), the only difference is, that the destination is different (console compared to file). And that's basically the same with System.out.






The underlying OS operation (displaying chars on a console window) is slow because





  1. The bytes have to be sent to the console application (should be quite fast)

  2. Each char has to be rendered using (usually) a true type font (that's pretty slow, switching off anti aliasing could improve performance, btw)

  3. The displayed area may have to be scrolled in order to append a new line to the visible area (best case: bit block transfer operation, worst case: re-rendering of the complete text area)


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...