1

In C# is it faster to access

value =  array[i];

or

fixed(Type123* pointerOfArray = arrayOfType123)
value =  *(pointerOfArray+i)

Is there any difference between these operations? Is there a way unsafe and fixed could improve its access ?

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
Lau Llobet
  • 577
  • 7
  • 21
  • 7
    Why don't you write some benchmarks and find out for yourself? – David Crowell Aug 13 '14 at 18:16
  • 14
    Not that it's a bad question to know the answer to, but I feel like if you're worried about performance to that degree, C# might not be the best language for what you're doing. – Matthew Haugen Aug 13 '14 at 18:16
  • 1
    Accessing the array will do bounds checking which I don't think would be done using the pointer, but I think this performance increase would be negligible unless you are doing mission critical code. I could be way off on this, though. – Dismissile Aug 13 '14 at 18:16
  • 2
    Without accepted answer but nonetheless - http://stackoverflow.com/questions/5374815/true-unsafe-code-performance – Eugene Podskal Aug 13 '14 at 18:17
  • 3
    If you've identified array access as being an actual bottleneck by profiling, it should be a relatively simple task to set up a similar benchmark to compare the pointer alternative to see if it changes things. – Ken White Aug 13 '14 at 18:19
  • 2
    @DavidCrowell: Because that's not the way it should be done. The OP's benchmark would only give them the results for a single test, using a single compiler, on a single architecture. SO should aim to provide better answers than that. – Douglas Aug 13 '14 at 18:20
  • @Douglas: Stack Overflow isn't really the place to crowdsource benchmarks on various platforms. – Robert Harvey Aug 13 '14 at 20:34
  • 1
    @RobertHarvey: I wasn't suggesting that. I meant that SO should aim to provide substantive answers, such as the underlying reasons why one operation might be faster than the other (e.g. array bounds checking). – Douglas Aug 13 '14 at 20:39

0 Answers0