6 ms·
I've heard bind is slow. Is this still true?
by pencilcode 13y ago
I've heard bind is slow. Is this still true?
- spion 13y agoyes
- vectorjohn 13y agoSlow in what way? If you think about what it's doing, it can only be so slow. Assuming the browser's engine doesn't do any sort of optimization (bind is a native method, so it might), it is simply creating an anonymous function that calls the original. So it's an extra function call: var boundFn = function(){ return originalFunction.apply( this, [boundArg1, boundArg2].concat( arguments ) ); } or something like that.
- kevingadd 13y agoIt's significantly slower than doing it by hand because of how .bind() is implemented in v8 and spidermonkey. It messes with the type information the engines use to optimize and it often sends you through C++ to do the function call.
- cjfont 13y agoSo is it .bind() itself that is slow, or the function that it returns? Assuming the bind operation itself is done during initialization, its slowness is pretty irrelevant.
- kevingadd 13y agoBind itself is slower than doing it by hand with a closure, and the return value is an order of magnitude slower than the hand-written closure and pollutes type information for your entire application, making all your code slower.
- rtpg 13y agowhy not use a "JS-native"implemtation then? Are there some issues with the spec that need to be respected?
- kevingadd 13y agoI'm not aware of any good reason to use Function.bind. Presumably at some point in the future VMs could optimize it such that it would be faster than a native JS polyfill, but right now the polyfill is superior. If you just want to slam out some JS one-liners, though, you obviously want to use built-in functions where possible.
- vectorjohn 13y agoCould you link to something supporting this claim? I'd be interested, because it sounds pretty unbelievable. I don't know how "sending you through C++" could be slow, and I wouldn't want anyone basing any decisions on a random HN comment.