xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Chrome V8 引擎源码剖析

Chrome V8 引擎源码剖析

V8

https://github.com/v8/v8

array & sort

https://github.com/v8/v8/search?l=JavaScript&o=desc&p=1&q=array.js&s=

https://github.com/v8/v8/tree/master/test/js-perf-test/Array

Array Sort

https://github.com/v8/v8/tree/master/test/js-perf-test/ArraySort

https://github.com/v8/v8/blob/master/test/js-perf-test/ArraySort/sort.js

https://github.com/v8/v8/blob/master/test/js-perf-test/ArraySort/sort-base.js


const kArraySize = 4000;
let template_array = [];

for (let i = 0; i < kArraySize; ++i) {
  template_array[i] = Math.floor(Math.random() * kArraySize);
}

let array_to_sort = [];


function Sort() {
  array_to_sort.sort();
}

function CreateSortFn(comparefns = []) {
  return () => {
    for (let cmpfn of comparefns) {
      array_to_sort.sort(cmpfn);
    }
  }
}

function cmp_smaller(a, b) {
  if (a < b) return -1;
  if (b < a) return 1;
  return 0;
}

function cmp_greater(a, b) { return cmp_smaller(b, a); }

// The counter is used in some benchmarks to trigger actions during sorting.
// To keep benchmarks deterministic, the counter needs to be reset for each
// iteration.
let counter = 0;

// Sorting benchmarks need to execute setup and tearDown for each iteration.
// Otherwise the benchmarks would mainly measure sorting already sorted arrays
// which, depending on the strategy, is either the worst- or best case.
function createSortSuite(name, reference, run, setup, tearDown = () => {}) {
  let run_fn = () => {
    counter = 0;

    setup();
    run();
    tearDown();
  };

  return createSuite(name, reference, run_fn);
}

Fisher-Yates shuffle 洗牌算法


const shuffle = (arr = []) => {
    for (let i = 1; i < arr.length; i++) {
        const random = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[random]] = [arr[random], arr[i]];
    }
    return arr;
};

const sort = (arr = []) => {
    arr.sort(() => Math.random() > .5);
    return arr;
};

const Test = func => {
    // 以下均测试10,000,000次打乱,记录最后的结果于一个二维数组count
    // count[i][j]即表示数字i在j位置出现的次数
    const total = 10000000;
    const count = [...new Uint8Array(5)].map(() => [...new Uint8Array(5)]);
    const arr = [0, 1, 2, 3, 4];
    for (let i = 0; i < total; i++) {
        func(arr).forEach((n, i) => count[n][i]++);
    }
    // 输出百分比,四舍五入保留2位小数
    console.table(count.map(n => n.map(n => (n / total * 100).toFixed(2) + '%')));
};

Test(shuffle);
Test(sort);

refs

JavaScript 数组乱序

https://www.zhihu.com/question/68330851

v8 在处理 sort 方法时,使用了插入排序和快排两种方案。当目标数组长度小于10时,使用插入排序;反之,使用快排。???

https://github.com/v8/v8/blob/master/src/js/array.js



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-07-29 12:22  xgqfrms  阅读(1574)  评论(4编辑  收藏  举报