Learn more about JavaScript caching

青灯夜游
Release: 2020-11-06 17:55:02
forward
2755 people have browsed it

Learn more about JavaScript caching

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
  • Higher-order function (function that returns a function)

Closure

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
Copy after login

From this code, we can determine three scopes:

  • Global scope (containsfooas a unique identifier)
  • fooscope, which has identifiersa,b, andbar
  • ## barscope, containingcidentifier
Looking carefully at the above code, we notice that function

foocan access variables a and b, because It is nested withinfoo. Note that we successfully stored functionbarand its execution environment. Therefore, we say thatbarhas a closure on the scope offoo.

You can understand this in the context of genetics, where individuals have the opportunity to acquire and express genetic traits even outside of their current environment. This logic highlights another element of closure, leading to This brings us to our second main concept.

Returning functions from functions

Functions that accept other functions as parameters or return other functions are called higher-order functions.
Closures allow us to call inner functions outside of the enclosing function while maintaining access to the enclosing function's lexical scope

Let's make some adjustments to the code in the previous example to Explain this.

function foo(){ var a = 2; function bar() { console.log(a); } return bar; } var baz = foo(); baz();//2
Copy after login

注意函数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, …
Copy after login

或者

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
Copy after login

挑战:编写一个函数返回斐波那契数列中的n元素,其中的序列是:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …]
Copy after login

知道每个值都是前两个值的和,这个问题的递归解是:

function fibonacci(n) { if (n 

确实简洁准确!但是,有一个问题。请注意,当 n 的值到终止递归之前,需要做大量的工作和时间,因为序列中存在对某些值的重复求值。

看看下面的图表,当我们试图计算 fib(5)时,我们注意到我们反复地尝试在不同分支的下标 0,1,2,3 处找到 Fibonacci 数,这就是所谓的冗余计算,而这正是缓存所要消除的。

Learn more about JavaScript caching

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] }
Copy after login

接下来,检查当前键n是否有缓存值,如果有,则返回其值。

和之前的解一样,我们指定了n小于等于1时的终止递归。

最后,我们递归地调用n值较小的函数,同时将缓存值(memo)传递给每个函数,以便在计算期间使用。这确保了在以前计算并缓存值时,我们不会第二次执行如此昂贵的计算。我们只是从memo中取回值。

注意,我们在返回缓存之前将最终结果添加到缓存中。

使用 JSPerf 测试性能

可以使用些链接来性能测试。在那里,我们运行一个测试来评估使用这两种方法执行fibonacci(20)所需的时间。结果如下:

Learn more about JavaScript caching

哇! ! !这让人很惊讶,使用缓存的 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 } } }
Copy after login

上面,我们简单地创建一个名为memoizer的新函数,它接受将函数fun作为参数进行缓存。在函数中,我们创建一个缓存对象来存储函数执行的结果,以便将来使用。

memoizer函数中,我们返回一个新函数,根据上面讨论的闭包原则,这个函数无论在哪里执行都可以访问cache

在返回的函数中,我们使用if..else语句检查是否已经有指定键(参数)n的缓存值。如果有,则取出并返回它。如果没有,我们使用函数来计算结果,以便缓存。然后,我们使用适当的键n将结果添加到缓存中,以便以后可以从那里访问它。最后,我们返回了计算结果。

很顺利!

要将 memoizer 函数应用于最初递归的fibonacci函数,我们调用memoizer函数,将fibonacci函数作为参数传递进去。

const fibonacciMemoFunction = memoizer(fibonacciRecursive)
Copy after login

测试 memoizer 函数

当我们将memoizer函数与上面的例子进行比较时,结果如下:

Learn more about JavaScript caching

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!