Skip to content

Instantly share code, notes, and snippets.

@bmeurer
Created September 20, 2017 20:55
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 bmeurer/4a40846a443dca9e3317ee7fad32159a to your computer and use it in GitHub Desktop.
Save bmeurer/4a40846a443dca9e3317ee7fad32159a to your computer and use it in GitHub Desktop.
Following up on discussion at @munichjs how to create packed arrays pre-initialized in V8
"use strict";
// These are examples how to created PACKED_*_ELEMENTS arrays preinitialized
// in V8, following up on offline discussion at the last MunichJS meetup.
function createPackedViaArrayFrom(length, value) {
return Array.from.call(null, Array.prototype.map.call({length}, _ => value));
}
function createPackedViaGenerator(length, value) {
return [...(function* gen() { while (--length >= 0) yield value; })()];
}
function createPackedViaPush(length, value) {
let result = [];
while (--length >= 0) result.push(value);
return result;
}
// Uncomment and verify via d8 --allow-natives-syntax
//
// if (!%HasFastPackedElements(createPackedViaPush(10, null)) ||
// !%HasFastPackedElements(createPackedViaGenerator(10, null)) ||
// !%HasFastPackedElements(createPackedViaArrayFrom(10, null))) {
// throw new Error("Oooops...");
// }
const TESTS = [
createPackedViaArrayFrom,
createPackedViaGenerator,
createPackedViaPush
];
const n = 1e6;
const length = 1024;
const value = null;
function test(fn) {
var result;
for (var i = 0; i < n; ++i) result = fn();
return result;
}
for (var j = 0; j < TESTS.length; ++j) {
test(TESTS[j]);
}
for (var j = 0; j < TESTS.length; ++j) {
var startTime = Date.now();
test(TESTS[j]);
console.log(TESTS[j].name + ':', (Date.now() - startTime), 'ms.');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment