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

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

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

  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>
相关推荐
TechMix5 小时前
【性能工具】atrace、systrace、perfetto抓取的trace文件有何不同?
android·性能优化
qq_5470261799 小时前
Java 中的 Caffeine 缓存详解
java·开发语言·缓存
devilnumber11 小时前
Redis 使用过程中可能遇到的常见问题或 “坑”
数据库·redis·缓存
山峰哥12 小时前
SQL性能飞跃:从索引策略到查询优化的全链路实战指南
数据库·sql·性能优化·深度优先
CDN36013 小时前
【踩坑实录】前端开发必看:一次由CSS缓存引发的线上事故与SEO反思
前端·css·缓存
Aray123414 小时前
Redis Cluster 集群选举机制
数据库·redis·缓存
ego.iblacat1 天前
Redis 核心概念与部署
数据库·redis·缓存
苏渡苇1 天前
5 分钟跑起 Redis(Docker 版)
数据库·redis·缓存·docker·redis入门
Jul1en_1 天前
【Redis】Zset类型、命令及应用场景
数据库·redis·缓存
杨凯凡1 天前
【014】基本类型与包装类:缓存、相等性、NPE
java·数据结构·缓存