1

I've found similar questions like so:

Java - Best way to print 2D array?

But they don't answer the question of- Is it more efficient?

I'm writing a basic little console game in C# that requires repeatedly clearing and writing to the console in order to refresh the game state. In searching for a more efficient way to do this than my current attempt, iterating through the array with a nested for loop and printing it that way, I found this in Java:

Arrays.deepToString(arrayName);

which does what I'm trying to achieve.

  1. Is this more efficient than using nested loops in Java like so?:

    String[][] map = new String[10][10];
    
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            map[i][j] = "=";
        }
    }
    
    boolean firstRun = true;
    
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            if (j == 0 && firstRun == false)
            {
                System.out.print("\n");
            }
    
            System.out.print(map[i][j]);
            firstRun = false;
        }
    }
    
  2. If it is more efficient, is there a C# library equivalent? I can't seem to find one or even someone asking about one anywhere.

1 Answers1

3

You are looking at this from the wrong angle:

  • your code is dealing with almost no data (10x10 is nothing in 2019)
  • your code is doing console output

Rest assured: printing to stdout like this is many times more expensive than processing a close-to-nothing array in memory (see here for some example data).

Thus, the real answer is: you can safely ignore performance aspects here.

Instead invest your time into writing code that is easy to read, understand, and maintain. Coming from there, that single call to Arrays.deepToString(arrayName); is very much to be preferred over writing custom loops doing the same.

Keep in mind: in the java world, runtime performance doesn't come out of writing "clever" source code. It comes out of the JIT deciding "this code is used so often, I should translate it to machine code". If the JIT thinks "not worth optimising" then it is not worth optimising. If it is worth optimising, make that easy for the JIT. By writing simple and easy code.

Long story short: it is a nice exercise to implement that functionality, but now that you achieved that, throw it away and use the library call that works for you.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    Although this isn't the code I was working with, I was just using it as an example, this definitely answers my question and helps a lot, thanks. – Jack Whelan Feb 28 '19 at 15:36