/    Sign up×
Community /Pin to ProfileBookmark

unshift vs push

Which of these array methods is less expensive?

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@rnd_meOct 29.2009 — [CODE]r=[1,2,3];
r[r.length]=4;
[/CODE]

is about 30% faster in IE than push...
Copy linkTweet thisAlerts:
@bsnoteauthorOct 29.2009 — Hi rnd_me,

Thanks for this.

I encountered performance problems. Currently I use unshift method to add items to the beginning of the buffer. But it seems there is more efficient way.

It is more appropriate to ask: what is the most efficient way to add items to an array (no matter, in the beginning or in the end)?
Copy linkTweet thisAlerts:
@rnd_meOct 29.2009 — Hi rnd_me,

Thanks for this.

I encountered performance problems. Currently I use unshift method to add items to the beginning of the buffer. But it seems there is more efficient way.

It is more appropriate to ask: what is the most efficient way to add items to an array (no matter, in the beginning or in the end)?[/QUOTE]


i posted it...

it's quicker to go to the end, since adding to the front requires re-indexing the whole array...

it a tightly controlled situation, you can get a 1-3% boost by using "++":

[CODE]var r=[1,2,3],[COLOR="Red"] mx[/COLOR]=r.length, ob={a:1,b:2};

for(it in ob){
r[[COLOR="Red"]mx++[/COLOR]]=ob[it];
}[/CODE]


this example is not worth it, but for bigger workloads ++ can save a little time compared to using array.length...

note that in firefox and chrome, these tweaks make little difference.

I chalk that up to those browser's "early optimizations".

The do howver make a lot of difference for naive script engines like those in IE and Opera.
Copy linkTweet thisAlerts:
@bsnoteauthorOct 30.2009 — This answers my question. Thanks rnd me.
×

Success!

Help @bsnote spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...