Javascript: What's the algorithmic performance of 'splice'?

匿名 (未验证) 提交于 2019-12-03 10:03:01

问题:

That is, would I be better suited to use some kind of tree or skip list data structure if I need to be calling this function a lot for individual array insertions?

回答1:

You might consider whether you want to use a straight map instead; all JavaScript objects (including Array instances) are maps, and so an implementation should (note I don't say "does") have a reasonable performance hashing algorithm.

Aside from that, the performance of splice is going to vary a lot between implementations (e.g., vendors). This is one reason why "don't optimize prematurely" is even more appropriate advice for JavaScript applications that will run in multiple vendor implementations (web apps, for instance) than it is even for normal programming. Keep your code well modularized and address performance issues if and when they occur.



回答2:

Here's a good rule of thumb, based on tests done in Chrome, Safari and Firefox: Splicing a single value into the middle of an array is roughly half as fast as pushing/shifting a value to one end of the array. (Note: Only tested on an array of size 10,000.)

http://jsperf.com/splicing-a-single-value

That's pretty fast. So, it's unlikely that you need to go so far as to implement another data structure in order to squeeze more performance out.

Update: As eBusiness points out in the comments below, the test performs an expensive copy operation along with each splice, push, and shift, which means that it understates the difference in performance. Here's a revised test that avoids the array copying, so it should be much more accurate: http://jsperf.com/splicing-a-single-value/19



回答3:

Move single value

//	tmp = arr[1][i]; //	arr[1].splice(i, 1);	// splice is slow in FF //	arr[1].splice(end0_1, 0, tmp);  	tmp = arr[1][i]; 	ii = i; 	while (ii


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!