性能安全与不安全

时间:2019-12-26 15:59:16

标签: c# performance unsafe heapsort

为什么下面的不安全代码与安全访问数组相比没有快得多?是什么导致速度变慢,以及如何更好地编写它的想法?我将尝试将Heapsort编辑为不安全。

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;
  }
}

(我不知道还要写些什么,但是自动检查仍然会报告: “看来您的帖子大部分是代码;请添加更多详细信息。”)

0 个答案:

没有答案