1

When I use inside for loops arr(j, i) = 5 it's 10-times slower than arr(i, j) = 5 why?

    Dim x As Integer = 10000
    Dim arr(x, x) As Integer


    Dim watch As Stopwatch
    watch = Stopwatch.StartNew()

    For i As Integer = 0 To x
        For j As Integer = 0 To x
            arr(j, i) = 5
        Next
    Next

    watch.Stop()

    ' arr(i, j) = 5 => TIME: 187
    ' arr(j, i) = 5 => TIME: 1615
    Console.WriteLine(watch.Elapsed.TotalMilliseconds())
Davidm176
  • 163
  • 1
  • 12
  • is it because of paging? – Davidm176 Jan 04 '17 at 21:39
  • [Cache misses](https://en.wikipedia.org/wiki/CPU_cache#Cache_miss) because of how they are located in memory. It can be a bit faster with jagged array http://stackoverflow.com/questions/468832/why-are-multi-dimensional-arrays-in-net-slower-than-normal-arrays – Slai Jan 04 '17 at 21:45
  • Does this answer your question? [C# Fastest dimension to traverse a 3D array](https://stackoverflow.com/questions/62231761/c-sharp-fastest-dimension-to-traverse-a-3d-array) – Guru Stron Dec 09 '22 at 12:01

0 Answers0