Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

arrays - Why is 'delete' slow in javascript?

I just stumbled upon this jsperf result: http://jsperf.com/delet-is-slow

It shows that using delete is slow in javascript but I am not sure I get why. What is the javascript engine doing behind the scene to make things slow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the question is not why delete is slow... The speed of a simple delete operation is not worth measuring...

The JS perf link that you show does the following:

  • Create two arrays of 6 elements each.
  • Delete at one of the indexes of one array.
  • Iterate through all the indexes of each array.

The script shows that iterating through an array o which delete was applied is slower than iterating though a normal array.

You should ask yourself, why delete makes an array slow?

The engine internally stores array elements in contiguous memory space, and access them using an numeric indexer.

That's what they call a fast access array.

If you delete one of the elements in this ordered and contiguous index, you force the array to mutate into dictionary mode... thus, what before was the exact location of the item in the array (the indexer) becomes the key in the dictionary under which the array has to search for the element.

So iterating becomes slow, because don't move into the next space in memory anymore, but you perform over and over again a hash search.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...