Should I prefer variables or multiple indirections on arrays in C# in perf critical code?

前端 未结 3 1248
再見小時候
再見小時候 2021-01-16 04:20

in some perf critical program (single threaded), if I have arrays of primitive types, and need to access the same index of those more than once in loops.

Should I us

相关标签:
3条回答
  • 2021-01-16 05:00

    Lets test this:

      int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7};
      int t = arr[3];
      int a = 0;
      var start = DateTime.UtcNow;
      for (int i = 0; i < 1000000000; i++)
      {
        a += t;
      }
      Console.WriteLine(a);
      Console.WriteLine(DateTime.UtcNow-start);
      a = 0;
      start = DateTime.UtcNow;
      for (int i = 0; i < 1000000000; i++)
      {
        a += arr[3];
      }
      Console.WriteLine(a);
      Console.WriteLine(DateTime.UtcNow - start);
    

    Output:

    -294967296
    00:00:02.1925000
    -294967296
    00:00:03.4250000
    

    Yes its slower to access the array repeatedly.

    0 讨论(0)
  • 2021-01-16 05:11

    Array access always involves indirection, so if there are frequent accesses the variable will likely be faster.

    That said, I find it incredibly unlikely that you will be able to measure the difference. This is an example of micro-optimization.

    0 讨论(0)
  • 2021-01-16 05:24

    In general access to an array is slower than a temporary because it has 2 additional pieces of overhead

    • A layer of indirection
    • A bounds check

    However I would not be changing any code I had today based on that knowledge unless a profiler clearly showed a tight loop to be a significant perf problem in my application. And furthermore showed that changing to a cached local produced a significant perf benefit.

    0 讨论(0)
提交回复
热议问题