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

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

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

  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>
相关推荐
大江东去浪淘尽千古风流人物10 小时前
【Project Aria】Meta新一代的AR眼镜及其数据集
人工智能·嵌入式硬件·算法·性能优化·ar·dsp开发
张彦峰ZYF11 小时前
解析 QLExpress 表达式预编译与缓存机制:Java 性能优化实践
性能优化·qlexpress表达式预编译·qlexpress表达式缓存·qlexpress 性能优化
BD_Marathon11 小时前
MyBatis的一级缓存
spring·缓存·mybatis
德迅云安全—珍珍11 小时前
什么是 DNS 缓存投毒攻击,有什么防护措施
网络·缓存
txinyu的博客11 小时前
CPU 缓存行
缓存
China_Yanhy11 小时前
唯快不破:区块链项目的 Redis 缓存选型与实战指南
redis·缓存·区块链
hanqunfeng21 小时前
(四十四)Redis8 新增的数据类型 -- Vector Set
数据库·redis·缓存
jiayong231 天前
Tomcat性能优化面试题
java·性能优化·tomcat
爬山算法1 天前
Hibernate(51)Hibernate的查询缓存如何使用?
spring·缓存·hibernate
虹科网络安全1 天前
艾体宝新闻 | Redis 月度更新速览:2025 年 12 月
数据库·redis·缓存