從 V8 原始碼看 JS 陣列排序的詭異問題

發表於2017-08-12

前幾天一個朋友在微信裡面問我一個關於 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 小於 ba 等於 ba 大於 b 這三種情況必須有一個為 true

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

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

如果 comparefn(a, b) 等於 0ab 的相對位置不變。備註: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 undefineds 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 > 0false,執行了 else 分支程式碼。


思考題,以下程式碼的結果:

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

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

justjavac

相關文章