Javascript: how much more efficient is forked function declaration?
Disabling any magic optimization performed using JIT / run-time is "worth it" in the same way as to call any function. Functions are simply objects that are often stored in variables (or properties).
How "effective" the version that returns a specialized object-object depends on factors, including (but not limited to):
- the number of times the resulting function is executed (1x = no gain) and
- the "cost" of the branch compared to another code (depends) and
- the "cost" of making the specified closure (very cheap)
For a cheap branch or a small number of executions, the amount of "efficiency" is reduced. If there is a specific precedent, then check this and you will have an βanswerβ.
When I see this, my immediate reaction is that it would be terrible to maintain. Code written this way cannot really be easily understood.
This example does not necessarily do it fairly, IMOHO and is useless for other reasons. I think that providing an anonymous external function with an explicit name - this can be done even for expression functions - could help, for example, clarify an intention. Write the code first to be clean. Then run benchmark analysis and correct if necessary. The likelihood of "slow parts" will not be what was originally expected.
Some of them are "not easy to understand" - it is simply ignorance of this construction (without implying anything negative here), on the other hand, every language that I know about has functions that are abused in cases where there are cleaner solutions.
In this case, instead of conditionally defining the function inside another function, which is then called immediately after the declaration of the external function, you can write a function of nested ifs. That would be longer, but, in my opinion, easier to understand (although I come from C / C ++ / Java).
Again, the exact case seems messy, IMOHO. However, JavaScript is not C / C ++ / Java, and function-like-first-class values ββand closures do not exist in C / C ++ / Java (this is a little white lie, closures can be emulated in Java, and newer C ++ supports some AFAIK closure form - but I do not use C ++).
Thus, this construct is not considered in these other languages ββbecause other languages ββdo not support it easily (or in general) - it does not say anything about the viability of the approach (in JavaScript or elsewhere) in general.
I would prefer answers that include some test numbers or explanations of how these functions will differ at runtime.
See above.
Deploy the highlighted bold portion at the top:
A function is "just an object" that is "applied" (read: called) with an operator (...) .
function x () { alert("hi") } x()
Happy coding.
user166390
source share