lru_cache vs cache

在Python中,lru_cachecache都是functools模块提供的装饰器,用于缓存函数的结果,但它们的功能和使用场景略有不同。

functools.lru_cache

lru_cache表示"最近最少使用"缓存。它是一个装饰器,用于缓存函数调用的结果。当缓存达到设定的最大容量时,会丢弃最近最少使用的缓存项。这对于一些计算量大且频繁调用的函数非常有用。

  • 语法@functools.lru_cache(maxsize=128, typed=False)

  • 参数

    • maxsize:指定缓存的最大容量。如果设置为None,缓存大小不受限制。
    • typed:如果设置为True,则会将不同类型的参数视为不同的调用(例如,f(3)f(3.0)会分别缓存)。
  • 示例

    python 复制代码
    from functools import lru_cache
    
    @lru_cache(maxsize=100)
    def expensive_function(x):
        # 模拟耗时计算
        return x * x

functools.cache

cache是一个更简单版本的缓存装饰器。它是lru_cache(maxsize=None)的别名,表示提供一个不受限制的缓存。这在需要缓存所有函数调用结果且不考虑缓存淘汰策略时非常有用。

  • 语法@functools.cache

  • 示例

    python 复制代码
    from functools import cache
    
    @cache
    def expensive_function(x):
        # 模拟耗时计算
        return x * x

关键区别

  1. 淘汰策略

    • lru_cache:使用最近最少使用的淘汰策略。当缓存达到最大容量时,丢弃最近最少使用的项。
    • cache:没有淘汰策略,缓存项数量不受限制。
  2. 定制化

    • lru_cache:允许设置缓存大小(maxsize)和类型敏感性(typed)。
    • cache:没有定制化选项,相当于lru_cache(maxsize=None)

使用场景

  • lru_cache:适用于需要限制内存使用且对使用顺序敏感的缓存场景。
  • cache:适用于需要简单且不受限制的缓存场景。

leetcode

题目:https://leetcode.cn/problems/special-permutations/description/

我讲下述代码提交后,发现 @lru_cache(maxsize=None) 时间超时, @cache 能够成功提交;

建议大家leetcode 刷题的时候,还是使用 @cache 好一点,简单无脑还快一点;

python 复制代码
class Solution:
    def specialPerm(self, nums: List[int]) -> int:

        @cache
        # @lru_cache(maxsize=None)
        def dfs(rear:int, lefts: tuple):
            if len(lefts) == 0:
                return 1

            res = 0
            for item in lefts:
                if item % rear == 0 or rear % item == 0:
                    res += dfs(item, tuple(set(lefts) - set([item])))
            
            return res % (1e9 + 7)
            

        res = 0
        for item in nums:
            res += dfs(
                    item, 
                    tuple(set(nums) - set([item]))
                )

        return int(res % (1e9 + 7))
相关推荐
写个博客38 分钟前
暑假算法日记第二天
算法
ChaITSimpleLove1 小时前
.NET9 实现排序算法(MergeSortTest 和 QuickSortTest)性能测试
算法·排序算法·.net·benchmarkdotnet·datadog.trace
CVer儿1 小时前
svd分解求旋转平移矩阵
线性代数·算法·矩阵
Owen_Q1 小时前
Denso Create Programming Contest 2025(AtCoder Beginner Contest 413)
开发语言·算法·职场和发展
Wilber的技术分享2 小时前
【机器学习实战笔记 14】集成学习:XGBoost算法(一) 原理简介与快速应用
人工智能·笔记·算法·随机森林·机器学习·集成学习·xgboost
巴里巴气2 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19892 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金2 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
Tanecious.2 小时前
LeetCode 876. 链表的中间结点
算法·leetcode·链表
ansurfen2 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm