如何进行更好的面试回复之缓存函数在项目中的性能优化?

缓存函数是一种提高函数性能的技术,在函数被调用时,会将计算结果缓存起来,以便在后续的调用中直接返回缓存的结果,从而减少了重复计算的时间。

缓存函数的实现通常包括两个步骤:

  1. 判断缓存是否存在:在函数被调用时,首先判断缓存对象中是否已经存在该参数对应的缓存结果,如果有则直接返回缓存结果,否则进入下一步。

  2. 计算并缓存结果:如果缓存不存在,则进行函数的计算,并将计算结果保存到缓存对象中,然后返回计算结果。

使用缓存函数可以大大提高程序的性能,特别是对于一些需要耗费大量时间计算的函数,例如递归计算、数学公式计算等。但需要注意的是,由于缓存函数的缓存对象会占用一定的内存空间,因此需要适度使用缓存函数,避免出现内存溢出等问题。

首先查看以下的代码,当我每次点击的时候,都会打印一次5以内的随机数,那么每次都要进行一次请求。这时我们就可以将数据进行一个缓存,当我们再次打印相同的结果时,直接返回缓存中的结果。

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>缓存函数在项目中的性能优化</title>
</head>
<body>
    <h1>缓存函数在项目中的性能优化</h1>
    <button id="fetchButton">获取数据</button>
    <div id="resultContainer">
        <script>
            function fetchDataFromServer(postId) {
                console.log('从服务器端获取数据:', postId)
            }

            const fetchButton = document.getElementById("fetchButton")
            const resultContainer = document.getElementById("resultContainer")

            fetchButton.addEventListener("click",() => {
                const postId = Math.floor(Math.random() * 5) + 1
                //调用这个函数传递参数
                fetchDataFromServer(postId)
            })
        </script>
    </div>
</body>

</html>

这时,我们定义一个缓存函数

复制代码
function createCachedFunction(originalFunction){
    const cache = {};
    return function(arg){
        if(cache[arg]){
            console.log("从缓存中进行数据获取",arg)
            return Promise.resolve(cache[arg])
        }
    } 

    return originalFunction(arg).then(result => {
        cache[arg] = result;
        console.log('第一次进行数据获取,并实现了缓存',arg);
        return result;
    })
}

定义之后我们也要去使用这个函数

复制代码
const cacheFetchData = createCachedFunction(fetchDataFromServer)

fetchButton.addEventListener("click",() => {
    const postId = Math.floor(Math.random() * 5) + 1
    // fetchDataFromServer(postId)
    cacheFetchData(postId).then(data => {
        resultContainer.innerHTML =  `<pre>${JSON.stringify(
            data,
            null,
            2
        )}</pre>`
    })
})

全部代码为下列

复制代码
<h1>缓存函数在项目中的性能优化</h1>
    <button id="fetchButton">获取数据</button>
    <div id="resultContainer">
        <script>
            // 
            function fetchDataFromServer(postId) {
                console.log('从服务器端获取数据:', postId)
                return fetch(
                    `https://jsonplaceholder.typicode.com/posts/${postId}`
                ).then(response => response.json());
            }

            function createCachedFunction(originalFunction){
                const cache = {};
                return function(arg){
                    if(cache[arg]){
                        console.log("从缓存中进行数据获取",arg)
                        return Promise.resolve(cache[arg])
                    }
                } 

                return originalFunction(arg).then(result => {
                    cache[arg] = result;
                    console.log('第一次进行数据获取,并实现了缓存',arg);
                    return result;
                })
            }

            const cacheFetchData = createCachedFunction(fetchDataFromServer)

            const fetchButton = document.getElementById("fetchButton")
            const resultContainer = document.getElementById("resultContainer")

            fetchButton.addEventListener("click",() => {
                const postId = Math.floor(Math.random() * 5) + 1
                // fetchDataFromServer(postId)
                cacheFetchData(postId).then(data => {
                    resultContainer.innerHTML =  `<pre>${JSON.stringify(
                        data,
                        null,
                        2
                    )}</pre>`
                })
            })
        </script>
    </div>
相关推荐
是梦终空2 天前
React Native 性能优化指南
react native·性能优化
侑虎科技3 天前
在UE5中,预测脚步IK实现-PredictFootIK
性能优化·unreal engine
bluceli5 天前
前端性能优化实战指南:让你的网页飞起来
前端·性能优化
冰_河6 天前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
叶智辽7 天前
【Three.js内存管理】那些你以为释放了,其实还在占着的资源
性能优化·three.js
BigByte8 天前
我用 6 个 WASM 编码器干掉了 Canvas.toBlob(),图片压缩率直接提升 15%
性能优化·webassembly·图片资源
DemonAvenger9 天前
Kafka性能调优:从参数配置到硬件选择的全方位指南
性能优化·kafka·消息队列
桦说编程9 天前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
小马爱打代码10 天前
MySQL性能优化核心:InnoDB Buffer Pool 详解
数据库·mysql·性能优化
顾青10 天前
仅仅一行 CSS,竟让 2000 个节点的页面在弹框时卡成 PPT?
前端·vue.js·性能优化