简体   繁体   中英

Printing many characters vs printing one string

I am currently using this code to print all of the characters in a 2D array, 10,000 in total.

char[][] charMap = new char[100][100]
for(int i = 0; i < charMap.length; i++)
{
    for(int j = 0; j < charMap[0].length; j++)
    {
        System.out.print(String.valueOf(charMap[i][j]));
        System.out.print(" ");
    }
    System.out.println("");
}

Would it run faster if I added all the chars to a string variable so there would only be one println function? I imagine editing a variable could be significantly faster than printing.

Since everyone is telling you to test for yourself, I'll try to help by providing some code that you can use to test this.

Firstly, we'll time printing the character matrix (or as you call it, charMap).

char[][] charMap = new char[100][100];
long startTime = System.currentTimeMillis();
for(int i = 0; i < charMap.length; i++)
{
    for(int j = 0; j < charMap[0].length; j++)
    {
        System.out.print(charMap[i][j]);
        System.out.print(" ");
    }
    System.out.println("");
}
System.out.println((System.currentTimeMillis() - startTime) + " ms");

Then, we'll construct a string using a loop, then print the entire string at the very end. Now, we'll do the same, except print a string for each iteration of the outer loop.

char[][] charMap = new char[100][100];
    long startTime = System.currentTimeMillis();
    for(int i = 0; i < charMap.length; i++)
    {
        StringBuilder sb = new StringBuilder();
        for (char c : charMap[i]) {
            sb.append(c).append(" "); //since you want the space
        }
        System.out.println(sb.toString());
    }
    System.out.println((System.currentTimeMillis() - startTime) + " ms");

Try both for yourself and see how it goes.

Note: I know you didn't ask for this, but I'm also curious about the overhead of the StringBuilder. If you didnt need the space between each element in a row, you could use this instead:

for(int i = 0; i < charMap.length; i++)
{
    System.out.println(charMap[i]);
}

Edit: I'm gonna run some of these tests myself, and will be back soon with the results. :)

I am populating my matrix like this:

Random r = new Random();
String a = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < charMap.length; i++) 
    for (int i1 = 0; i1 < charMap[i].length; i1++) 
        charMap[i][i1] = a.charAt(r.nextInt(a.length()));

I am not timing the population of the matrix.

Okay, so with the first implementation, with printing out every indexed character followed by a space, I get an eyeball average of 110-140 ms.

With the second method of using a StringBuilder, I am getting an average of 14-30 ms.

Finally, with the last method with omitting the spaces, I get an average of 3-9 ms.

Notes: This is not the best way to benchmark a program, since Java does things such as "lazy-load" classes. You'll need to look into proper benchmarking techniques to actually get a real evaluation for the performance. However, I doubt this matters that much, so using this naive approach would work fine, as long as you run it a few times (I ran each test 10 times) to get a ballpark idea.

Would it run faster if I added all the chars to a string variable so there would only be one println function?

Answer is YES, it would run faster.
But dont use String , use StringBuilder instead, because if you use String it will create 10,000 literals in String constant pool which results in high memory utilization and will slow down your program with time. And StringBuilder append() method will eliminate this problem.

Code:-

char[][] charMap = new char[100][100];
StringBuiler str=new StringBuilder();
for(int i = 0; i < charMap.length; i++)
{
    for(int j = 0; j < charMap[0].length; j++)
    {
       str.append(charMap[i][j]); // System.out.print(String.valueOf(charMap[i][j]));
       str.append(" ");           // System.out.print(" ");
    }
    str.append("\n");             //System.out.println("");
}

System.out.println(str);          // print created String

It will run faster than System.out.println because Java IO is much much expensive operation than StringBuilder Append.

I went ahead to wrote up a speed test as suggested.

import java.util.Scanner;

public class StringSpeedTest 
{
    public static void main(String[] args) 
    {
        long time1 = 0;
        char[][] charMap = new char[100][100];
        for(int i = 0; i < charMap.length; i++)
        {
            for(int j = 0; j < charMap.length; j++)
            {
                charMap[i][j] = '-';
            }
        }

        long startTime = System.currentTimeMillis();
        for(int k = 0; k < 100; k++)
        {       
            for(int i = 0; i < charMap.length; i++)
            {
                for(int j = 0; j < charMap[0].length; j++)
                {
                    System.out.print(charMap[i][j]);
                    System.out.print(" ");
                }
                System.out.println("");
            }
        }
        long endTime = System.currentTimeMillis();

        time1 = endTime - startTime;

        startTime = System.currentTimeMillis();
        for(int k = 0; k < 100; k++)
        {
            String strToPrint = "";
            for(int i = 0; i < charMap.length; i++)
            {
                for(int j = 0; j < charMap[0].length; j++)
                {
                    strToPrint+=charMap[i][j];
                    strToPrint+=" ";
                }
                strToPrint+="\n";
            }
            System.out.println(strToPrint);
        }
        endTime = System.currentTimeMillis();
        System.out.println("First time: " + time1 + " ms");
        System.out.println("Second time: " + (endTime - startTime) + " ms");

        Scanner sc = new Scanner(System.in);
        sc.nextInt();
    }
}

I looped the pieces of code 100 times, so that I would get a good average. Here is the result.

First time: 82110 ms
Second time: 17999 ms

So adding the chars to a string and then printing the result takes about 22% of the time printing the chars individually takes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM