相关疑难解决方法(0)

为什么打印"B"比打印"#"要慢得多?

我生成了两个1000x 矩阵1000:

第一矩阵:O#.
第二个矩阵:OB.

使用以下代码,第一个矩阵需要8.52秒才能完成:

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("#");
        }
    }

   System.out.println("");
 }
Run Code Online (Sandbox Code Playgroud)

使用此代码,第二个矩阵需要259.152秒才能完成:

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) …
Run Code Online (Sandbox Code Playgroud)

java performance loops for-loop system.out

2662
推荐指数
3
解决办法
23万
查看次数

为什么System.out.println这么慢?

这是所有编程语言的共同点吗?进行多次打印然后使用println似乎更快但将所有内容移动到字符串并且只是打印似乎最快.为什么?

编辑:例如,Java可以在不到一秒的时间内找到所有素数高达100万 - 但是打印然后在他们自己的println上全部打印可能需要几分钟!打印高达100亿小时!

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{ …
Run Code Online (Sandbox Code Playgroud)

java performance

13
推荐指数
2
解决办法
1万
查看次数

标签 统计

java ×2

performance ×2

for-loop ×1

loops ×1

system.out ×1