javascript功能

    技术2022-07-11  79

    javascript功能

    Efficiency in code execution is incredibly important, especially when the given function is used repeatedly.  You often see repeated function calls within JavaScript frameworks.  When you work on said frameworks, you need to ensure you've hit ever micro-optimization possible.  One micro-optimization you can make is running conditionals before you create a function, instead of each time the function runs.  Let me illustrate a basic example.

    代码执行效率非常重要,特别是当重复使用给定功能时。 您经常会在JavaScript框架中看到重复的函数调用。 当您使用上述框架时,您需要确保已实现微优化。 您可以进行的一种微优化是在创建函数之前而不是每次函数运行时都运行条件语句。 让我说明一个基本的例子。

    坏人 (The Bad)

    The following would be considered inefficient:

    以下内容将被认为效率低下:

    function something() { if('something' in obj) { // something } else { // fallback } }

    The code above is inefficient because the conditional is run upon each call of the function.  Let's do better!

    上面的代码效率低下,因为条件调用是在每次调用函数时运行的。 让我们做得更好!

    善良 (The Good)

    Instead of running the conditional check within every function call, run the conditional before setting the function:

    代替在每个函数调用中运行条件检查,而是在设置函数之前运行条件检查:

    var something = ('something' in obj) ? function() { // something } : function() { // fallback };

    This pattern is especially applicable when using feature detection -- i.e. the value of the conditional never changing.  Of course the conditional evaluation is fast but why calculate easy conditionals more than once? You shouldn't, of course.  Keep this pattern in mind when creating your own frameworks -- don't repeat code!

    此模式在使用特征检测时特别适用-即条件的值永不更改。 当然,条件评估的速度很快,但为什么要多次计算简单的条件呢? 当然不应该。 创建自己的框架时,请牢记此模式-不要重复代码!

    翻译自: https://davidwalsh.name/feature-detection-function-efficiency-javascript

    javascript功能

    Processed: 0.011, SQL: 9