從 V8 源碼看 JS 數組排序的詭異問題

shelockid 7年前發布 | 25K 次閱讀 排序算法 JavaScript開發 JavaScript

前幾天一個朋友在微信里面問我一個關于 JS 數組排序的問題。

原始數組如下:

var data = [
  {value: 4}, 
  {value: 2}, 
  {value: undefined}, 
  {value: undefined}, 
  {value: 1}, 
  {value: undefined}, 
  {value: undefined}, 
  {value: 7}, 
  {value: undefined}, 
  {value: 4}
];

data 是個數組,數組的每一項都是一個擁有 value 作為 key 的對象,值為數字或者 undefined 。

data
  .sort((x, y) => x.value - y.value)
  .map(x => x.value);

對數組的 value 進行排序,然后把排完序的數組進行 flat 處理。得到的結果如下:

[2, 4, undefined, undefined, 1, undefined, undefined, 7, undefined, 4]

顯然這沒有達到我們的目的。

現在我們修改一下排序,挑戰一下函數的調用順序:先對數組進行扁平化(flat)處理,然后再排序。

data
  .map(x => x.value)
  .sort((x, y) => x - y)

這時我們得到的結果和之前截然不同:

[1, 2, 4, 4, 7, undefined, undefined, undefined, undefined, undefined]

遇到這種情況第一感覺肯定是要去看看 ECMA 規范,萬一是 JS 引擎的 bug 呢。

在 ES6 規范 22.1.3.24 節寫道:

Calling comparefn(a,b) always returns the same value v when given a specific pair of values a and b as its two arguments. Furthermore, Type(v) is Number , and v is not NaN . Note that this implies that exactly one of a < b , a = b , and a > b will be true for a given pair of a and b .

簡單翻譯一下就是:第二個參數 comparefn 返回一個數字,并且不是 NaN 。一個注意事項是,對于參與比較的兩個數 a 小于 b 、 a 等于 b 、 a 大于 b 這三種情況必須有一個為 true 。

所以嚴格意義上來說,這段代碼是有 bug 的,因為比較的結果出現了 NaN 。

在 MDN 文檔上還有一個細節:

如果 comparefn(a, b) 等于 0 , a 和 b 的相對位置不變。備注:ECMAScript 標準并不保證這一行為,而且也不是所有瀏覽器都會遵守。

翻譯成編程術語就是: sort 排序算法是不穩定排序。

其實我們最疑惑的問題上,上面兩行代碼為什么會輸出不同的結果。我們只能通過查看 V8 源碼去找答案了。

V8 對數組排序是這樣進行的:

如果沒有定義 comparefn 參數,則生成一個(高能預警,有坑啊):

comparefn = function (x, y) {
  if (x === y) return 0;
  if (%_IsSmi(x) && %_IsSmi(y)) {
    return %SmiLexicographicCompare(x, y);
  }
  x = TO_STRING(x);   // <----- 坑
  y = TO_STRING(y);   // <----- 坑
  if (x == y) return 0;
  else return x < y ? -1 : 1;
};

然后定義了一個插入排序算法:

function InsertionSort(a, from, to) {
  for (var i = from + 1; i < to; i++) {
    var element = a[i];
    for (var j = i - 1; j >= from; j--) {
      var tmp = a[j];
      var order = comparefn(tmp, element);
      if (order > 0) {   // <---- 注意這里
        a[j + 1] = tmp;
      } else {
        break;
      }
  }
  a[j + 1] = element;
}

為什么是插入排序?V8 為了性能考慮,當數組元素個數少于 10 個時,使用插入排序;大于 10 個時使用快速排序。

后面還定義了快速排序函數和其它幾個函數,我就不一一列出了。

函數都定義完成后,開始正式的排序操作:

// %RemoveArrayHoles returns -1 if fast removal is not supported.
var num_non_undefined = %RemoveArrayHoles(array, length);

if (num_non_undefined == -1) {
  // There were indexed accessors in the array.
  // Move array holes and undefineds to the end using a Javascript function
  // that is safe in the presence of accessors.
  num_non_undefined = SafeRemoveArrayHoles(array);
}

中間的注釋:Move array holes and undefined s to the end using a Javascript function。排序之前會把數組里面的 undefined 移動到最后。因此第二個排序算法會把 undefined 移動到最后,然后對剩余的數據 [4,2,1,7,4] 進行排序。

而在第一種寫法時,數組的每一項都是一個 Object,然后最 Object 調用 x.value - y.value 進行計算,當 undefined 參與運算時比較的結果是 NaN 。當返回 NaN 時 V8 怎么處理的呢?我前面標注過,再貼一次:

var order = comparefn(tmp, element);
if (order > 0) {  // <---- 這里
  a[j + 1] = tmp;
} else {
  break;
}

NaN > 0 為 false ,執行了 else 分支代碼。

思考題,以下代碼的結果:

[1, 23, 2, 3].sort()

掃碼二維碼關注我的公眾號

 

來自:https://segmentfault.com/a/1190000010630780

 

 本文由用戶 shelockid 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!