-1

Arrays are all of type Array, instead of their underlying type, meaning making arrays out of your own custom primitives with event handling and stuff is useless. Someone on Discord said that it'll probably take either reflection or unsafe constructs. Adding code to the get accessor is useless, because Array.Sort() only calls that accessor twice. What should I do instead to call code like events whenever an array element is accessed (like read or written)?

Here's what I'm trying to make, a benchmarker for sorting algorithms that charts the number of comparisons and total array accesses on a whole range of array sizes Sort benchmarker

1 Answers1

1

If you just want to count the number of comparisons you should probably provide an IComparer<T> implementation instead. Most sorting implementations take such an interface.

If you want to measure the number of accesses you need to use another interface, like IList<T>. But this will not be usable for most built in sort methods, since accessing elements thru an interface will reduce performance.

But measuring "array access" is probably not a meaningful metric. In many cases this will just be a memory access, and the time of this varies greatly depending on locality. A register access is "free", while a uncached memory read is many hundreds of cycles. So using profilers or writing an actual benchmark will probably be a much better tool to measure overall performance.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • My benchmarker is for generic sorters, and Array.Sort only takes T[] as input instead of IList. List has Sort(), but it just calls Array.Sort on its own internal array and only counts it as a single change – AceOfSpadesProduc100 Jul 19 '22 at 14:01
  • @AceOfSpadesProduc100 I have revised my answer. – JonasH Jul 19 '22 at 14:30
  • By "array accesses", I mean when an array index is read or written to. – AceOfSpadesProduc100 Jul 19 '22 at 23:02
  • @AceOfSpadesProduc100 But how is the number of index operations relevant? It has as best a very weak relation to actual performance. – JonasH Jul 20 '22 at 06:31
  • The actual performance will also be recorded. Instead of only recording the number of comparisons and how fast in ms it is, the number of index operations should also be recorded. – AceOfSpadesProduc100 Jul 20 '22 at 20:00