I recently tried to optimize some code for an often created value object. (A three dimensional vector, fwiw)
One thing I tried was to convert the constructor function from an anonymous method factory pattern to a normal JavaScript constructor.
This led to a severe performance penalty which surprised me, since the use of ‘new’ and normal constructors was much recommended in my last question on the subject of JavaScript constructor/factory patterns.
It could well be that my test is too simplistic, or just plain wrong, or a result of recent performance optimizations made in chrome’s JavaScript engine, or all of the above. In any case, I’d really like to know why my ‘optimizations’ led to performance drop – and – most important: Is there any obvious problem with my jsperf testrun?
One of the things that a constructor function optimizes for is shared properties, usually methods. If a number of objects use the same functions as methods, or share other named properties, then one assignment to the prototype will share a single instance of the property among all objects created from the constructor, reducing memory overhead, and will not need to repeat the assignment of each such property for every object created, reducing construction time overhead.
Since your sample does not include any such properties, you’re not going to see such benefits. But if your production code does not include shared properties for your constructed object, there might well be no reason to switch to a constructor.
So, if, for example you had code like this:
it will probably run more slowly than this:
It will also take a lot more memory if you create many instances.