[QUESTION] Which version of this function is faster? Why?

Our goal is to fill a two-dimensional array with 1’s.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

namespace ToArrays
{
    public class Program
    {
        public const int Size = 10000;

        private static void Main()
        {
            BenchmarkRunner.Run<Program>();
        }

        [Benchmark]
        public void IxJ()
        {
            var array = new int[Size, Size];
            for (var i = 0; i < Size; i++)
            {
                for (var j = 0; j < Size; j++)
                {
                    array[i, j] = 1;
                }
            }
        }

        [Benchmark]
        public void JxI()
        {
            var array = new int[Size, Size];
            for (var i = 0; i < Size; i++)
            {
                for (var j = 0; j < Size; j++)
                {
                    array[j, i] = 1;
                }
            }
        }
    }
}

Could you say which version is faster and why?

Compartilhe este insight:

6 respostas

  1. Yan Justino Vou arriscar 😀 Acredito que apesar dos dois algoritimos aparentemente terem a mesma complexidade (Θ(nˆ2)), a degradação do segundo é maior, uma vez que pra cada “i” eu preciso realizar uma operação Θ(n) no “j”, enquanto na primeira estratégia o custo é pago na primeira iteração de “i” e as demais eu tenho um custo de Θ(1) para a sua leitura.

  2. Nice question, indeed.

    I didn’t run the code (yet), but probably the JxI method is slower.

    It has to do with memory layout and how the 10000^2 allocations will be performed, it can goes basically two ways… like:

    [0, 1]
    [0, 2]
    [0, 3]
    [0, …]

    or:

    [1, 0]
    [2, 0]
    [3, 0]
    […, 0]

    Depending on how memory is allocated by the runtime one of the two methods will be slower.

    The fastest one will basically reads memory addresses ‘sequentially’ and the other will ‘jump’ 10000 addresses on each iteration.

    The fastest one will have addresses nearby, the slower will not. The problem is not with the ‘jump’ per se, since accessing an array by its index is usually O(1).

    The real problem is CPU cache, the slower method will perform a lot of cache misses, forcing the CPU to access RAM (which is slower than cache).

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Elemar Júnior

Sou fundador e CEO da EximiaCo e atuo como tech trusted advisor ajudando diversas empresas a gerar mais resultados através da tecnologia.

Mais insights para o seu negócio

Veja mais alguns estudos e reflexões que podem gerar alguns insights para o seu negócio:

Conheci o poema maravilhoso da Viviane Mosé, transcrito abaixo, na interpretação de uma grande amiga. Quem tem olhos pra ver...
Neste post mostro como implementar um EventBus, utilizando RabbitMQ, em C#. Este código ainda está em desenvolvimento. Em breve, uma...
Ao utilizar recursos não gerenciados, em .NET, precisamos garantir que estes sejam devidamente liberados. Para isso, quando criamos classes que...
As you probably noted, my old blog posts are gone! It’s sad, but I had to take this way. Main reasons:...
When designing systems that need to scale you always need to remember that using better resources could help you to...
Quando iniciei a EximiaCo, busquei implantar, na empresa, características minhas que valorizava e que achava que poderiam fazer diferença. Sabia,...
× Precisa de ajuda?