为什么System.out.println这么慢? [英] Why is System.out.println so slow?

查看:135
本文介绍了为什么System.out.println这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是所有编程语言共有的东西吗?在进行多次打印后再执行println似乎更快,但是将所有内容移至字符串,然后进行打印似乎最快.为什么?

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?

例如,Java可以在不到一秒钟的时间内找到所有高达100万的素数-但是将它们全部打印在自己的println上可能要花费几分钟!最多可以打印100亿小时!

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 );
            }
        }
    }
}

推荐答案

println并不慢,它是由主机操作系统提供的与控制台连接的基础PrintStream.

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

读取和写入与文件的大小相似(O(n)),并且成正比,唯一的区别是目的地不同(控制台与文件相比).基本上与System.out相同.

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. 必须将字节发送到控制台应用程序(应该非常快)
  2. 每个字符都必须使用(通常)真字体显示(这很慢,关闭反锯齿可以提高性能,顺便说一句)
  3. 可能需要滚动显示的区域才能在可见区域中添加新行(最好的情况:位块传输操作,最坏的情况:重新渲染整个文本区域)

这篇关于为什么System.out.println这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆