|
|
|
|
|
by raphaelrk
1686 days ago
|
|
Interesting! As a quick test on Chrome ("Version 95.0.4638.69 (Official Build) (x86_64)") t0 = new Date();
a = Array(100000000).fill(0);
console.log("time elapsed: ", new Date() - t0); // 22912
a[100000] = 1;
a[10000000] = 1;
a.forEach(e => e == 1 && console.log(e));
console.log("time elapsed: ", new Date() - t0); // 28371
t1 = new Date();
a = Array(100000000);
a[100000] = 1;
a[10000000] = 1;
a.forEach(e => e == 1 && console.log(e));
console.log("time elapsed: ", new Date() - t1); // 2787
Upon doing a couple not-so-scientific runs of this, it looks like the latter isn't really faster than the former. |
|
So what this code demonstrates is that if you have to look up a billion keys, that is going to be slower than if you have to look up two keys for an object.
Additional reading for this: https://v8.dev/blog/fast-properties From this article:
const sparseArray = []; sparseArray[9999] = 'foo'; // Creates an array with dictionary elements. In this example, allocating a full array with 10k entries would be rather wasteful. What happens instead is that V8 creates a dictionary where we store a key-value-descriptor triplets. The key in this case would be '9999' and the value 'foo' and the default descriptor is used. Given that we don't have a way to store descriptor details on the HiddenClass, V8 resorts to slow elements whenever you define an indexed properties with a custom descriptor: