作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有许多对字符串进行操作的函数,以从这些字符串中提取有趣的属性。被许多函数调用的一个特定函数非常昂贵,并最终生成一个值表:
local function expensive(s)
local t = nil
return function()
if not t then
t = {}
-- some expensive operations with s which add items to t
end
return t
end
end
local function fn1(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local function fn2(s)
local t = expensive(s)
-- some other fast operations using t and s
end
local s1, s2 = 'a', 'b'
fn1(s1) -- should create the 't' table for s1
fn1(s2) -- should create the 't' table for s2
fn2(s1) -- should not create the 't' table again for s1
fn1(s2) -- should also not create the 't' table again for s2
如何才能使昂贵的函数为每个字符串创建一次表,并在任一情况下返回表?我宁愿不让 table 暴露在全局环境中。我认为这可能可以通过巧妙地使用闭包来完成,但我不太了解其构造。
最佳答案
local cache = {}
local function expensive(s)
local t = cache[s]
if not t then
t = {}
-- some expensive operations with s which add items to t
cache[s] = t
end
return t
end
关于lua - 在 Lua 中的单独函数调用之间缓存字符串上昂贵的表计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44052959/
我正在阅读 MongoDB,并试图了解它的最佳用途。我没有看到明确答案的一个问题是哪些操作便宜或昂贵,以及在什么条件下。 你能帮忙澄清一下吗? 谢谢。 最佳答案 人们经常声称 mongodb 的写入速
我正在寻找一个主要来源(或一个非常好的解释)来支持在为 iPhone 编写软件时使用 autorelease 是危险的或过于昂贵的说法。 许多开发者都提出了这种说法,我什至听说 Apple 不推荐它,
我意识到这离微优化领域太远了,但我很想知道为什么调用 DateTime.Now 和 DateTime.UtcNow 如此“昂贵”。我有一个示例程序,它运行几个场景来做一些“工作”(添加到一个计数器)并
我是一名优秀的程序员,十分优秀!