1

Why is unsafe code below compared to safe access to array not much faster? What slows down and ideas how to write it better? I'll try to edit Heapsort as unsafe.

public unsafe static void HeapSortU(double[] array, int low, int high)
{
  int length = high - low + 1;
  fixed (double* arrPtr = array, start = &array[low], stred = &array[low + length / 2 - 1], root = &array[high])
  {
    for (double* i = stred; i >= start; i--)
      HeapifyU(start, root, i);
    for (double* i = root; i >= start; i--)
    {
      double temp = *start;
      *start = *i;
      *i = temp;
      HeapifyU(start, i, start);
    }
  }
}

private unsafe static void HeapifyU(double* start, double* root, double* bottom)
{
  double* l, largest;
  while (true)
  {
    largest = bottom;                    // initialize largest as root 
    l = bottom + (bottom - start) + 1;   // left = 2*bottom + 1 
    if (l < root && *l > *largest)
      largest = l;
    l++;                                 // right = 2*bottom + 2 
    if (l < root && *l > *largest)
      largest = l;
    if (largest != bottom)
    {
      double temp = *bottom;
      *bottom = *largest;
      *largest = temp;
      bottom = largest;
    }
    else
      break;
  }
}

(I don't know what else to write, but the automatic check still reports: "It looks like your post is mostly code; please add some more details.")

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • Possible duplicate of https://stackoverflow.com/questions/5374815/true-unsafe-code-performance –  Dec 26 '19 at 16:14
  • 1
    Why are you trying to optimize it? Are you simply curious, or is the performance necessary? But if I had to guess, I would say that plain old GC'd C# is probably a lot faster and better optimized than you might assume. – Slothario Dec 26 '19 at 16:16
  • 5
    The only benefit from this kind of unsafe code is that it will not perform any array index checks. On modern machines that doesn't buy you that much, accessing memory is many times more expensive than the check. Especially so if you don't access it in cache-friendly way or the array is large. Don't forget to compare to Array.Sort(). – Hans Passant Dec 26 '19 at 16:19
  • Does this answer your question? [True Unsafe Code Performance](https://stackoverflow.com/questions/5374815/true-unsafe-code-performance) – Julian Dec 26 '19 at 16:29

0 Answers0