As our applications continue to grow and begin to perform complex calculations, the need for speed becomes higher and higher, so optimization of the process becomes essential. When we ignore this problem, we end up with a program that takes a lot of time and consumes a lot of system resources during execution.
Recommended tutorial: "JavaScript Video Tutorial"
Caching is an optimization technique that stores the results of expensive function executions and reappears with the same input Cached results are returned, speeding up your application.
If this doesn't mean much to you, that's okay. This article explains in depth why caching is necessary, what caching is, how to implement it, and when you should use caching.
What is caching
Caching is an optimization technique by storing the results of expensive function executions and retrieving them again with the same input Return cached results when they occur, speeding up your application.
At this point, we are clear that the purpose of caching is to reduce the time and resources spent performing "expensive function calls".
What are Expensive Function Calls? Don’t get confused, we are not spending money here. In the context of computer programs, the two main resources we have are time and memory. Therefore, an expensive function call refers to a function call that takes up a lot of computer resources and time during execution due to the large amount of calculation.
However, just like money, we need to save. For this purpose, caches are used to store the results of function calls for quick and easy access at future times.
A cache is simply a temporary data storage that saves data so that future requests for that data can be processed faster.
So when an expensive function is called once, the result is stored in the cache, so that whenever the function is called again in the application, the result is fetched from the cache very quickly, without having to re-compute any calculations.
Why is caching important?
The following is an example that illustrates the importance of caching:
Imagine, You are in the park reading a new novel with an attractive cover. Every time a person passes by, they are attracted to the cover, so they ask about the title and author. The first time you are asked this question, you open the book and read the title and author's name. Now more and more people are coming here asking the same question. You are a very nice person, so you answer all questions.
Will you open the cover and tell him the title of the book and the author's name one by one, or start answering from memory? Which one will save you more time?
Discover the similarities Got it? Using mnemonics, when a function is provided with input, it performs the required calculations and stores the results in the cache before returning the value. If the same input is received in the future, it doesn't have to repeat it over and over again, it just has to provide the answer from cache (memory).
How caching works
The concept of caching in JavaScript is mainly based on two concepts, which are:
Closure is A combination of a function and the lexical environment in which the function is declared.
Not very clear? I think so too.
For better understanding, let’s quickly study the concept of lexical scope in JavaScript. Lexical scope simply refers to the physical location of variables and blocks specified by the programmer when writing code. The following code:
function foo(a) { var b = a + 2; function bar(c) { console.log(a, b, c); } bar(b * 2); } foo(3); // 3, 5, 10
From this code, we can determine three scopes:
foo
as a unique identifier)foo
scope, which has identifiersa
,b
, andbar
scope, containing
cidentifier
foocan access variables a and b, because It is nested within
foo. Note that we successfully stored function
barand its execution environment. Therefore, we say that
barhas a closure on the scope of
foo.
function foo(){ var a = 2; function bar() { console.log(a); } return bar; } var baz = foo(); baz();//2
注意函数foo
如何返回另一个函数bar
。这里我们执行函数foo
并将返回值赋给baz
。但是在本例中,我们有一个返回函数,因此,baz
现在持有对foo
中定义的bar
函数的引用。
最有趣的是,当我们在foo
的词法作用域之外执行函数baz
时,仍然会得到a
的值,这怎么可能呢?
请记住,由于闭包的存在,bar
总是可以访问foo
中的变量(继承的特性),即使它是在foo
的作用域之外执行的。
案例研究:斐波那契数列
斐波那契数列是什么?
斐波那契数列是一组数字,以1 或 0 开头,后面跟着1,然后根据每个数字等于前两个数字之和规则进行。如
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
或者
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
挑战:编写一个函数返回斐波那契数列中的n元素,其中的序列是:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …]
知道每个值都是前两个值的和,这个问题的递归解是:
function fibonacci(n) { if (n确实简洁准确!但是,有一个问题。请注意,当
n
的值到终止递归之前,需要做大量的工作和时间,因为序列中存在对某些值的重复求值。看看下面的图表,当我们试图计算
fib(5)
时,我们注意到我们反复地尝试在不同分支的下标0,1,2,3
处找到 Fibonacci 数,这就是所谓的冗余计算,而这正是缓存所要消除的。function fibonacci(n, memo) { memo = memo || {} if (memo[n]) { return memo[n] } if (n在上面的代码片段中,我们调整函数以接受一个可选参数
memo
。我们使用memo
对象作为缓存来存储斐波那契数列,并将其各自的索引作为键,以便在执行过程中稍后需要时检索它们。memo = memo || {}Copy after login
在这里,检查是否在调用函数时将memo
作为参数接收。如果有,则初始化它以供使用;如果没有,则将其设置为空对象。
if (memo[n]) { return memo[n] }
接下来,检查当前键n
是否有缓存值,如果有,则返回其值。
和之前的解一样,我们指定了n
小于等于1
时的终止递归。
最后,我们递归地调用n值较小的函数,同时将缓存值(memo
)传递给每个函数,以便在计算期间使用。这确保了在以前计算并缓存值时,我们不会第二次执行如此昂贵的计算。我们只是从memo
中取回值。
注意,我们在返回缓存之前将最终结果添加到缓存中。
使用 JSPerf 测试性能
可以使用些链接来性能测试。在那里,我们运行一个测试来评估使用这两种方法执行fibonacci(20)
所需的时间。结果如下:
哇! ! !这让人很惊讶,使用缓存的 fibonacci 函数是最快的。然而,这一数字相当惊人。它执行126,762 ops/sec,这远远大于执行1,751 ops/sec
的纯递归解决方案,并且比较没有缓存的递归速度大约快 99%。
注:“ops/sec”表示每秒的操作次数,就是一秒钟内预计要执行的测试次数。
现在我们已经看到了缓存在函数级别上对应用程序的性能有多大的影响。这是否意味着对于应用程序中的每个昂贵函数,我们都必须创建一个修改后的变量来维护内部缓存?
不,回想一下,我们通过从函数返回函数来了解到,即使在外部执行它们,它们也会导致它们继承父函数的范围,这使得可以将某些特征和属性从封闭函数传递到返回的函数。
使用函数的方式
在下面的代码片段中,我们创建了一个高阶的函数memoizer
。有了这个函数,将能够轻松地将缓存应用到任何函数。
function memoizer(fun) { let cache = {} return function (n) { if (cache[n] != undefined) { return cache[n] } else { let result = fun(n) cache[n] = result return result } } }
上面,我们简单地创建一个名为memoizer
的新函数,它接受将函数fun
作为参数进行缓存。在函数中,我们创建一个缓存对象来存储函数执行的结果,以便将来使用。
从memoizer
函数中,我们返回一个新函数,根据上面讨论的闭包原则,这个函数无论在哪里执行都可以访问cache
。
在返回的函数中,我们使用if..else
语句检查是否已经有指定键(参数)n
的缓存值。如果有,则取出并返回它。如果没有,我们使用函数来计算结果,以便缓存。然后,我们使用适当的键n
将结果添加到缓存中,以便以后可以从那里访问它。最后,我们返回了计算结果。
很顺利!
要将 memoizer 函数应用于最初递归的fibonacci
函数,我们调用memoizer
函数,将fibonacci
函数作为参数传递进去。
const fibonacciMemoFunction = memoizer(fibonacciRecursive)
测试 memoizer 函数
当我们将memoizer
函数与上面的例子进行比较时,结果如下:
memoizer
函数以42,982,762 ops/sec的速度提供了最快的解决方案,比之前考虑的解决方案速度要快 100%。
关于缓存,我们已经说明什么是缓存 、为什么要有缓存和如何实现缓存。现在我们来看看什么时候使用缓存。
何时使用缓存
当然,使用缓存效率是级高的,你现在可能想要缓存所有的函数,这可能会变得非常无益。以下几种情况下,适合使用缓存:
缓存库
总结
使用缓存方法 ,我们可以防止函数调用函数来反复计算相同的结果,现在是你把这些知识付诸实践的时候了。
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Learn more about JavaScript caching. For more information, please follow other related articles on the PHP Chinese website!