Why is 'delete' slow in javascript?

后端 未结 2 1590
伪装坚强ぢ
伪装坚强ぢ 2020-12-21 05:38

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. W

2条回答
  •  甜味超标
    2020-12-21 06:00

    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.

提交回复
热议问题