Skip to content

Instantly share code, notes, and snippets.

@wthit56
Forked from anonymous/gist:4427822
Last active December 10, 2015 11:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wthit56/4427971 to your computer and use it in GitHub Desktop.
Save wthit56/4427971 to your computer and use it in GitHub Desktop.
// run here (use the data-uri below as an address):
// data:text/html;ascii,<script src="https://gist.github.com/raw/4427971/cef83fed8b6de8bfbb9fa3ae461b724fff87c057/gistfile1.js" type="text/javascript"></script>
// The technique used here is based on an article by Ashley Gullen: http://netm.ag/SWI0E5
// Array#slice returns an array with the seleted range of items.
// Because a new array is created every time you use this method, however,
// all these arrays are in memory, which means the JavaScript GC (Garbage Collection)
// has to collect up all of these unused arrays and throw them away.
// In performance-critical situations, such as in a game-loop that needs to run within
// 16ms (60 frames times per second), GC can really mess with your smooth animations and such.
// To stop slicing from creating new arrays each time, you can mutate the array itself instead.
Array.prototype.slice_mutate = function slice_mutate(from, to) {
// first we set the array's length to the item at the "to" position
this.length = to;
// any items that were after the "to" position will be discarded
// from the first item...
i = 0;
// ...loop through all items before the "from" position...
while (from--) {
// ...removing each item as we go
this.shift();
}
// we have now removed all items before the "from" position
// and after the "to" position
// and so the array now contains a slice of items between positions
// "from" and "to".
return this;
};
// console shim
(function () {
if (!window.console) { window.console = {}; }
var c = window.console;
if (!c.log) { c.log = function () { }; }
if (!c.group) { c.group = function (label) { c.log("__" + label + "__"); }; }
if (!c.groupEnd) { c.groupEnd = function () { }; }
})();
// tests
var a = ["a", "b", "c", "d"];
console.group("a.slice(1,3)");
console.log("a: ", a);
console.log("returns: ", a.slice(1, 3));
console.log("after: ", a);
console.groupEnd();
var b = ["a", "b", "c", "d"];
console.group("b.slice_mutate(1,3)");
console.log("returns: ", b.slice_mutate(1, 3));
console.log("after: ", b);
console.groupEnd();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment