2015-01-21

Array.sort(comparator)

  • no comparator Array.sort() do string comparison(ASCII)

    [1, 2, 21, 3, -4].sort();
    //=> -4, 1, 2, 21, 3
  • self-define comparator

    var employees = [];
    employees[0] = {
    name: “George”,
    age: 32,
    retiredate: “March 12, 2014”
    };
    
    employees[1] = { name: “Edward”, age: 17, retiredate: “June 2, 2023” };
    employees[2] = { name: “Christine”, age: 58, retiredate: “December 20, 2036” };
    employees[3] = { name: “Sarah”, age: 62, retiredate: “April 30, 2020” };
    // retiredate ASC employees.sort(function(a, b) { return new Date(a.retiredate) - new Date(b.retiredate) });
    // age ASC employees.sort(function(a, b) { return a.age - b.age });
    类似

Array.forEach(callback)

The Array.forEach method, added in the fifth edition of the ECMA-262 language standard, take callback function and passes each array element to the function.

不同方式数组遍历、性能对比

计算一千万个数字相加求和,e1是包含一千万个数字的数组,对比结果如下:

  • 通过indexed定位元素

    console.time(“[Index] locate element”);
    var total2 = 0;
    for (var i = 0; i < e1.length; i++) {
    total2 = total2 + e1[i];
    }
    console.timeEnd(“index locate element”);
    //=> [Index] locate element: 160.000ms
    
    通过下标,准确定位,性能最佳。

  • 传递参数、调用算法函数

    function iterator(group) {
    var total0 = 0;
    for (var i = 0; i < group.length; i++) {
    total0 = total0 + group[i]; } } console.time(“function call”); iterator(e1); console.timeEnd(“function call”); //=> function call: 180.000ms
    [性能损耗] 参数传递,伴随”入栈、出栈“。

  • javascript native forEach

    console.time(“js native forEach”);
    var total1 = 0;
    e1.forEach(function(item) {
    total1 = total1 + item;
    });
    console.timeEnd(“js native forEach”);
    //=> js native forEach: 567.000ms
    [性能损耗] 每个元素都去调用Function

  • [for in ] iterator element

    console.time(“for in locate element”);
    var total3 = 0;
    for (var g in e1) {
    total3 = total3 + g;
    }
    console.timeEnd(“for in locate element”);
    //=> for in locate element: 3054.000ms
    [性能损耗] 几乎每个元素,都去iterator数组。性能最差。

 

Summary

针对底层数据结构是基于数组的集合:在进行大数据遍历时,建议通过indexed定位、避免全数组遍历。 如:javaArrayList