gpt4 book ai didi

actionscript-3 - Splice 比 Shift + Pop 快吗?为什么?

转载 作者:行者123 更新时间:2023-12-03 23:32:19 25 4
gpt4 key购买 nike

我从一些非特定来源听说使用 shift() 的组合和 pop()比使用 splice() 快.我还没有运行基准测试,而且很可能不会因为我出城而有一段时间,但这是真的吗,如果是这样,为什么?

最佳答案

如果您不需要保留数组的顺序,请使用 .pop().splice() 快得多.
.splice()将删除给定索引处的元素。然后发生的情况是,在此之后数组中的每个其他元素都需要将其在数组中的位置减 1。如果您的数组很大并且删除元素的索引很小,这可能会很慢。

使用 .pop() ,您可以完全删除重新索引所有内容的过程。您可以使用 .pop(),而不是删除给定索引处的元素。从数组中删除最后一项。从这里开始,您需要做的就是将要删除的项目替换为使用 .pop() 获得的项目。 .如前所述,这当然意味着您的元素的顺序没有得到维护。

代码示例:
.splice() :

var list:Array = [0,1,2,3,4,5];
list.splice(2, 1);

trace(list); // 0,1,3,4,5

然后 .pop() :
var last:* = list.pop();
list[2] = last;

trace(list); // 0,1,5,4 - Notice we move 5 to the index 2 and lose the order.

在这里,我们有非常重要的实际性能测试:
var list:Array = [];
function fillList():void
{
for(var i = 0; i < 200000; i++) list.push(i);
}


function emptyViaSplice():void
{
fillList();
var t:Number = getTimer();

while(list.length > 0)
{
list.splice(0, 1);
}

trace("emptyViaSplice: " + (getTimer() - t));
}


function emptyViaPop():void
{
fillList();
var t:Number = getTimer();

while(list.length > 0)
{
if(list.length == 1) list.pop();
else
{
var l:* = list.pop();
list[0] = l;
}
}

trace("emptyViaPop: " + (getTimer() - t));
}

结果:
emptyViaSplice(); // 12153 ms
emptyViaPop(); // 37 ms

关于actionscript-3 - Splice 比 Shift + Pop 快吗?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15052782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com