简体   繁体   中英

Performance penalty JavaScript callback-functions

Is there a performance penalty when using callback functions (in JavaScript), opposed to using it in a synchronous manner?

For instance:

method(function(result){});

Instead of

var result = method();

Edit: And if there is an overhead introduced by the callback functions, I would love to know why.

Thanks in advance!

Thereis a teeny tiny overhead for using callback-functions in synchronous computation compared to return.
Yes, callbacks can be used in a synchronous way. Check out CPS ; or for consistency reasons in the API.

This overhead comes through the overhead of clling a function and maintaining the call-stack, and since you often use closures as callbacks, there is a little overhead to create them, too.

But this would be micro-optimizations, comparable to replacing a v * 2 with v << 1 (for performance reasons).
If you have to optimize such things in your code, you have some really serious problems in the structure of your application.

The only problem to be mentioned when calling callbacks synchronously, is the possibility to exceed the maximum stack-size at some point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM