[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:

Se há algo que nunca vi foi consenso para o significado de “produto pronto” nas as áreas de desenvolvimento, marketing...
Há tempos, venho pensando sobre “mérito”. Superficialmente, quanto dos meus resultados, positivos e negativos, se devem exclusivamente a mim? Descartando...
I wrote this post in 2016. Unfortunately, I lost it when I “rebooted” my blog. Anyway, I have a good...
Não são raros os casos onde a distância entre um “desejo” e a “realização” é a “tentativa”. Ou seja, partindo...
In this post, I would like to explain a basic but confusing concept of CUDA programming: Thread Hierarchies. It will...
Há algum tempo, estou compartilhando recomendações práticas para construção de microsserviços com Aspnet Core.  Agora, resolvi organizar meus exemplos para...
× Precisa de ajuda?