0

Let's say I have a multidimensional array:

var arr = new double[2, 5, 5]
{
    {
        { 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1 },
        { 1, 1, 1, 1, 1 }
    },
    {
        { 1, 1, 1, 1, 1 },
        { 1, 2, 2, 2, 1 },
        { 1, 2, 2, 2, 1 },
        { 1, 2, 2, 2, 1 },
        { 1, 1, 1, 1, 1 }
    },
};

I want to copy 3 by 3 part of that array starting from index [1,1,1] till index [1,3,3] (all 2 values).

What is the most efficient way of doing so ? So far, I do it with a loop:

var arr2 = new int[3, 3];

int x_start = 1;
int y_start = 1;

for (int i = 0; i < arr2.GetLength(0); i++)
{
    for (int j = 0; j < arr2.GetLength(1); j++)
    {
        arr2[i, j] = arr[1, x_start + i, y_start + j];
    }
}

But I wonder if there is a more efficient way of doing it ?

1
  • That’s the most efficient way to do it. You are using fast loops and only loop over those indexes you are interested in. Commented Aug 6, 2018 at 22:46

1 Answer 1

1

poke already made the same point in their comment, but this is essentially the best way of doing this.

That’s the most efficient way to do it. You are using fast loops and only loop over those indexes you are interested in. - poke

You could possibly cache the two GetLength() calls in an integer, but I doubt that'd make any meaningful difference in performance.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.