by phpnode · 12y ago · 0 comments
There are many reasons to keep on using `new`, the biggest one is probably performance, `new Foo` will always outperform `Object.create(FooProto)`.
Really though, this kind of article just grinds my gears. There are so few absolutes in software development, articles like:
"You should always X"
"Stop doing Y"
almost always really mean "I don't actually understand X or Y"He's right, `new` is more than 10x faster in Chrome and Firefox for me at least:
Why would it `always outperform` though? Seems like an implementation detail. Object.create should be faster since it doesn't run a constructor.
If I create an interpreter that changes `new Foo` to `$new(Foo)` where $new is a JS function that uses Object.create to do what the `new` operator does in spec (e.g., treat it as syntactic sugar) then it's unlikely that `new Foo` would outperform `Object.create(FooProto)`. Just because the current interpreters are hyperfocusing on `new` doesn't mean they can't make `Object.create` faster in the future.
All requiring `new` does is add an implicit requirement that the name of your function is actually `new X` instead of `X` with the added requirement that all aliases of the function be prefixed with `new `, which is not composable.
Yeah, `new` might be faster than not using it right now, but that's a bug in the interpreters. And for a lot of objects, your inner loop is not going to be in creation.
`new Foo()` is faster because it can be compiled to more efficient code today and probably always will be. Your argument is a bit like the "given a sufficiently intelligent compiler" one, I don't care about what JS engines of the future might do, I care about my code's performance today.
If you meant that new is faster today, say so. That's not the same as "will always outperform".
`new Foo` has simpler semantics than `Object.create(FooProto)` and therefore I believe it will always be faster. That performance gap can of course narrow, but I think `new` will always be the fastest. Happy to be proved wrong.
For instance, if you want to use any of Google's Javascript libraries like their map api client, you're going to be using "new". So, now you've done a bunch of work to avoid using "new" but as soon as you step outside of your bubble, you're going to have to find a way to deal with "new" anyway. So, what's the point? Just use a good linter and be done with it.
Following an old-school technique just because you might see it in some legacy code doesn't seem like a great argument.