为什么我在 webassembly 中导出的快速排序比纯 javascript 实现慢?

Mic*_*Mic 5 javascript emscripten webassembly

我已经在纯 Javascript 和 C 中实现了一个非常简单的快速排序,后者被导出为 WebAssembly 模块。

我正在对[0;1000] 范围内的 2 个相同的 10 6 个整数数组进行排序。纯 javascript 实现平均需要 780 毫秒,而基于 WebAssembly 的实现需要 935 毫秒(未设置优化标志时为 1020 毫秒)。

为什么纯 javascript 实现最快?

在有问题的 2 个实现下面:

JS:

function swap(array, swapy1, swapy2) {
  let tmp = array[swapy1];
  array[swapy1] = array[swapy2];
  array[swapy2] = tmp;
}


function partition(array, lo, hi) {
  const pivot = array[hi];
  let i = lo - 1;
  for (let j = lo; j < hi; j++) {
    if (array[j] < pivot) {
      if (i !== j) {
        i++;
        swap(array, i, j)
      }
    }
  }
  i++;
  swap(array, i, hi);
  return i;
}

export default function sort(array, lo, hi) {
  if (lo < hi) {
    const p = partition(array, lo, hi);
    sort(array, lo, p - 1);
    sort(array, p + 1, hi);
  }
}
Run Code Online (Sandbox Code Playgroud)

C:

void swap(int *array, int swapy1, int swapy2) {
    int tmp = array[swapy1];
    array[swapy1] = array[swapy2];
    array[swapy2] = tmp;
  }


  int partition(int *array, int lo, int hi) {
    int pivot = array[hi];
    int i = lo - 1;
    for (int j = lo; j < hi; j++) {
      if (array[j] < pivot) {
        if (i != j) {
          i++;
          swap(array, i, j);
        }
      }
    }
    i++;
    swap(array, i, hi);
    return i;
  }

  void sort(int *array, int lo, int hi) {
    if (lo < hi) {
      int p = partition(array, lo, hi);
      sort(array, lo, p - 1);
      sort(array, p + 1, hi);
    }
  }

  void quicksort(int *array, int lo, int hi, char *exp) {
   struct timeval t1, t2;
   double elapsedTime;

    gettimeofday(&t1, NULL);
    sort(array, lo, hi);
    gettimeofday(&t2, NULL);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms

    printf(" - 10%s entries sorted in %.0f ms\n", exp, elapsedTime);
  }
Run Code Online (Sandbox Code Playgroud)

调用者代码(通过 emscripten Module 对象):

WasmModule().then(wasm => {
    console.log("Monothreaded Lomuto Quicksort, WebAssembly");
    function callWasm(array, exponant) {
      let heapBuf = wasm._malloc(array.length * Uint32Array.BYTES_PER_ELEMENT);
      wasm.HEAP32.set(array, heapBuf / 4);
      wasm.ccall('quicksort', null, ['number', 'number', 'number', 'string'], [heapBuf, 0, array.length - 1, exponant]);
      wasm._free(heapBuf);
    }
    millionIntCopy = millionInt.slice();
    tenMillionIntCopy = tenMillionIntCopy.slice();
    callWasm(millionIntCopy, "\u2076");
    // callWasm(tenMillionIntCopy, "\u2077"); // stack overflow
    // callWasm(hundredMillionInt, "\u2078"); stackoverflow
  })
Run Code Online (Sandbox Code Playgroud)

完整的项目可以在这里找到