简体   繁体   中英

Remove element of array without splice()

I'm developing a JavaScript game and I want to keep my memory usage as low as possible. Therefore I set some objects to null again, so they can get garbage collected. I read an article which recommends avoiding functions like Array.splice() , because this creates a new array, which allocates new memory.

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

What other ways exist to avoid using Array.splice ?

You need to realize how jsperf runs your code. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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