DEV Community

Discussion on: Subclassing arrays in JavaScript

Collapse
 
austindd profile image
Austin

It should be noted that extending the Array to a custom ES6 class can DRAMATICALLY reduce performance.

I tested in this in jsperf, and most operations, from array construction to the inherited '.map()' method, were over 1,000x slower with the custom array class. The ops/sec can go from millions to thousands, which IMO is far from negligible.

You can see my tests here: jsperf.com/class-extends-array

I'm curious about why the performance gap is so massive. After several hours of research, I can only speculate the following:

(1) Standard host Array instances come with some guarantees that the browser's compiler can rely on to optimize their performance, and subclassed arrays cannot provide those guarantees.

(2) Altering the internal [[prototype]] of the custom array object can lead to severe performance costs, hinted at in the MDN docs here:

developer.mozilla.org/en-US/docs/W...

and here:

developer.mozilla.org/en-US/docs/W...