在Actionscript中连接数组的最佳方法

时间:2011-01-13 21:11:26

标签: performance actionscript readability

我需要将一个数组添加到另一个数组(只关心保存连接的数组)。这是首选的方法吗?速度是可读性之后的主要关注点(我认为选项1是更清洁的选择)。我假设它可能还取决于数组的长度,但是有没有好的指导方针?

选项1:

var array1:Array = new Array("1","2","3");
var array2:Array = new Array("4","5","6");

// Don't care about array2 after this point.
var array1 = array1.concat(array2);

选项2:

var array1:Array = new Array("1","2","3");
var array2:Array = new Array("4","5","6");

// Don't care about array2 after this loop has run.
for each(var item:Object in array2)
{
    array1.push(item);
}

2 个答案:

答案 0 :(得分:9)

这听起来像......基准工作!

import flash.utils.getTimer;

function addItems($array:Array, $start:int, $count:int) {
    for (var i:Number = $start; i < $start + $count; i++) {
        $array.push(i);
    }
}

function concatArrays($array1:Array, $array2:Array):Number {
    var t1:Number = getTimer();
    $array1.concat($array2);
    var t2:Number = getTimer();
    return t2 - t1;
}

function pushArrays($array1:Array, $array2:Array):Number {
    var t1:Number = getTimer();
    for each (var item:Object in $array2) {
        $array1.push(item);
    }
    var t2:Number = getTimer();
    return t2 - t1;
}

function testBed() {
    for (var i:Number = 10000; i <= 100000; i+=10000) {
        trace("\n---- New test");
        var a1:Array = [];
        var a2:Array = [];
        addItems(a1, 0, i);
        addItems(a2, i, i);
        trace("For " + a1.length + " items: ");
        trace("concatArrays: " + concatArrays(a1, a2));
        trace("pushArrays:   " + pushArrays(a1, a2));
    }
}

testBed();

正如我所怀疑的那样,concat要快得多,特别是在处理更大的数组时。

输出

---- New test
For 10000 items: 
concatArrays: 1
pushArrays:   1

---- New test
For 20000 items: 
concatArrays: 1
pushArrays:   4

---- New test
For 30000 items: 
concatArrays: 1
pushArrays:   4

---- New test
For 40000 items: 
concatArrays: 2
pushArrays:   5

---- New test
For 50000 items: 
concatArrays: 1
pushArrays:   6

---- New test
For 60000 items: 
concatArrays: 1
pushArrays:   7

---- New test
For 70000 items: 
concatArrays: 1
pushArrays:   8

---- New test
For 80000 items: 
concatArrays: 2
pushArrays:   12

---- New test
For 90000 items: 
concatArrays: 2
pushArrays:   13

---- New test
For 100000 items: 
concatArrays: 3
pushArrays:   14

这些数字以毫秒为单位,正如理查德指出的那样,除非你的数组有大量的元素,或者你经常连接数组,那么这是一个不值得你时间的优化

答案 1 :(得分:4)

我会亲自使用concat,因为它更简单。

它可能也更快(因为它可以原生实现),但如果它对你很重要,请测量它。除非你正在处理极大数量的数组值,否则不太可能存在差异,并且将成为微优化的主要示例。

相关问题