简体   繁体   English

删除没有splice()的数组元素

[英]Remove element of array without splice()

I'm developing a JavaScript game and I want to keep my memory usage as low as possible. 我正在开发JavaScript游戏,并且我希望将内存使用率保持在尽可能低的水平。 Therefore I set some objects to null again, so they can get garbage collected. 因此,我将一些对象再次设置为null,以便可以收集垃圾。 I read an article which recommends avoiding functions like Array.splice() , because this creates a new array, which allocates new memory. 我读了一篇文章 ,建议避免使用Array.splice()类的函数,因为这会创建一个新数组,该数组分配新的内存。

So I've implemented a JSFiddle with an own function, that deletes an element at a specific index and shifts all elements behind, so the length will be set to length -= 1 . 因此,我实现了带有自己的函数的JSFiddle ,该函数删除特定索引处的元素并将所有元素移到后面,因此长度将设置为length- length -= 1 This only affects the existing array instead of creating a new one: 这只会影响现有阵列,而不会创建一个新阵列:

Function to use instead of splice: 要代替拼接使用的函数:

 deleteElem = function(arr, el) {
      var index = arr.indexOf(el);
      if (index > -1) {
        var len = arr.length - 1;
        for (var i = index; i < len; i++) {
          arr[i] = arr[i + 1];
        }
        arr.length = len;
      }
    }

The JSFiddle for my function is sometimes faster, sometimes slower... Should I pay more attention to better performance and worse memory, or better memory and worse performance? 用于我的功能的JSFiddle有时更快,有时更慢...我应该更多地关注更好的性能和更差的内存,还是更好的内存和更差的性能?

What other ways exist to avoid using Array.splice ? 还有什么其他方法可以避免使用Array.splice

You need to realize how jsperf runs your code. 您需要了解jsperf如何运行您的代码。 It doesn't run setup for each time it runs your code - the code runs hundreds or thousands of times for each setup. 它不会在每次运行您的代码时都运行安装程序-每次安装代码都会运行数百或数千次。

That means you are using an empty array for 99.999999% of the calls and thus not measuring anything useful. 这意味着您正在为99.999999%的呼叫使用一个空数组,因此没有测量任何有用的东西。

You could at least get some sense out of it by measuring it like this http://jsperf.com/splice-vs-own-function/2 however you need to note that the allocation of array of 50 times might blunt the differences and that your method is therefore actually much faster than the benchmark can show. 像这样http://jsperf.com/splice-vs-own-function/2进行测量,至少可以使您有所了解,但是您需要注意,分配50次数组可能会使差异变钝,并且因此,您的方法实际上比基准测试所显示的要快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM