【发布时间】:2010-12-14 09:37:48
【问题描述】:
这是所有编程语言共有的吗?在 println 之后进行多次打印似乎更快,但是将所有内容都移动到一个字符串中并且只打印似乎最快的。为什么?
编辑:例如,Java 可以在不到一秒的时间内找到最多 100 万的所有素数 - 但是在它们自己的 println 上打印所有素数可能需要几分钟!最多可打印 100 亿罐小时!
前:
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 的速度非常快……
-
@DasWood“好像”?请提供一些基准(代码+时间)。
-
它在 *nix 上往往很快,在 Windows 上很慢。换句话说,这些操作系统的控制台实现才是这里的因素。
-
基准我粘贴的示例,打印注释掉了。没有它。巨大的差异,它只通过数字线一次,而不是像实际的筛子那样 9999998 次。
-
不要重复println,而是把它全部放到一个字符串中,然后再println。它更快。
标签: java performance