Bashir Y B
Bashir Y B

Reputation: 5

How can I optimize this nested for loop in java?

for (int i = 0 ; i < row ; i++){
        for (int k = 0 ; k < col ; k++) {
            System.out.print("\t" + mat[i][k]);
        }

My objective is to reduce the execution time for a large value of rows and cols

Upvotes: 0

Views: 152

Answers (3)

Bhavya
Bhavya

Reputation: 16192

Each System.out.println takes time to execute. Currently in your code you are doing System.out.println for every element we can reduce it to almost one fourth by doing System.out.println for each row instead of doing for each column

NOTE:

Furthermore optimization can be done if you know beforehand how many rows and columns are there in your code. If there is a major difference in cardinality of rows and columns , then outer loop you can run with lower cardinality value.

You can see the below mentioned code :

StringBuilder sb=new StringBuilder();
for(int i=0; i<row; i++) 
{

    for(int j=0; j<col; j++) 
    {
        sb.append('\t');    
        sb.append(mat[i][j]);
    }
    sb.append('\n');
}
System.out.println(sb.toString());

Upvotes: 1

Stefan
Stefan

Reputation: 1803

I did not expect this but Elliot's comment is right. Bashir, you asked for an example, here it is:

public class Main
{

    private static void test()
    {
        int row = 1000;
        int col = 1000;
        int mat[][] = new int[row][col];

        StringBuilder buffer=new StringBuilder();

        for (int i = 0; i < row; i++)
        {
            for (int k = 0; k < col; k++)
            {
                //System.out.print("\t" + mat[i][k]);

                //System.out.print('\t');                
                //System.out.print(mat[i][k]);

                buffer.append('\t');
                buffer.append(mat[i][k]);
            }
        }
        System.out.println(buffer.toString());
    }

    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        test();
        long end = System.currentTimeMillis();
        System.err.println("Test took " + (end - start) + "ms");
    }
}

I executed it (on Linux) at the command-line to ensure that the performance of my terminal window or graphic card does not affect the measurement:

java Main > /dev/null

The buffered version runs 30x faster than the original.

Upvotes: 3

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79550

If you just intend to print your 2-D array, you can use Arrays.deepToString. However, you intend to print it in the format you have mentioned and still want to reduce the I/O operations, you can build a string using StringBuilder and print it. Note that both these options will cost you memory. The first option internally uses StringBuilder while in the second option, you will be building the string yourself using the StringBuilder. So, it's the number of I/O operations vs. memory utilization.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] mat = { { 10, 20 }, { 40, 30 } };

        System.out.println(Arrays.deepToString(mat));

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mat.length; i++) {
            for (int k = 0; k < mat[0].length; k++) {
                sb.append("\t" + mat[i][k]);
            }
            sb.append("\n");
        }
        System.out.println(sb);
    }
}

Output:

[[10, 20], [40, 30]]
    10  20
    40  30

Upvotes: 0

Related Questions