Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 904
gillesC Avatar asked Sep 03 '26 12:09

gillesC


1 Answers

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.

like image 175
Thomas Avatar answered Sep 06 '26 09:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!