My expectations before actually running the benchmarks were that of the 3 methods, pseudo classical would be the fastest, followed by composition and then last but not least, prototypal. My reasoning for my assumptions were:
- Prototypal should be the slowest because 2 objects are needed to create an instance, the prototype to base the new object on and a second object which must be iterated over and whose ‘hasown’ properties are copied to the new object.
- And finally composition, which I just assumed would always fall somewhere in the middle of the others.
The benchmark tests I created do not use the DOM at all, they merely create the intended object and they do not store them in memory. My goal was to create these tests so that they would be similar to putting a car on a dynamo, putting the transmission into neutral, and flooring the gas pedal.
Creating 1,000,000 Objects – The Benchmark Results
I was kind of surprised, actually, at the results. Not only were my assumptions not always right but it is clear that the 3 browsers that I tested on my Mac (all the latest versions of Chrome, Safari and Firefox as of February 27, 2013) are not all created equally when it comes to creating lots of objects… Not even by a long shot.
When Speed Counts, Think About How You Approach Object Creation
What is clear from my test results, though, is that Chrome’s virtual machine is by far and away the fastest of the 3 browsers when asked to create millions of objects. On average I’ve found that when using pseudo classical/new, in fact, it is almost 60 times faster when compared to Safari and almost 28 times faster when compared to Firefox. Things start to even out somewhat when using prototypal, but when it comes to using composition, Chrome once again blows the doors off the others being almost 10 times faster.
As my test have shown, if you are creating millions of objects as my tests did then you need to think about your approach and if time is really critical then maybe you should consider targeting each browser with a specific approach.
Get It On GitHub And Run The Tests
My repo on GitHub contains all the code I used to test. There are no other dependencies. I also included a nice little web page for initiating the tests and displaying the output though in order to view nanosecond based results you will have to view the results in the browser console.
I’m looking forward to hearing from you all, especially I’m interested in your reactions to the test results and even about the code that I wrote for benchmarking. Please feel free to leave your comments here.
Oh, one last note – I didn’t run these test on Windows or Linux so if someone would like to do that and comment on your finding here then that would be greatly appreciated. I am very curious regarding the effect that the OS has on the test results and the results for the latest versions of IE.