我们需要缓存数组吗? [英] Do we need cache for an array?
问题描述
由于我们正在使用django开发一个基于Web的项目。我们缓存数据库操作以实现更好的性能。但是我想知道是否需要缓存数组。
Since we're developing a web-based project using django. we cache the db operation to make a better performance. But I'm wondering whether we need cache the array.
这样的代码示例:
ABigArray = {
"1" : {
"name" : "xx",
"gender" "xxx",
...
},
"2" : {
...
},
...
}
class Items:
def __init__(self):
self.data = ABigArray
def get_item_by_id(self, id):
item = cache.get("item" + str(id)) # get the cached item if possible
if item:
return item
else:
item = self.data.get(str(id))
cache.set("item" + str(id), item)
return item
我想知道我们是否真的需要这样的缓存,因为当尝试获取一个项目时,IMO的数组( ABigArray )将被加载到内存中。所以我们不需要在这种情况下使用缓存,对吧?或者我错了?
So I'm wondering whether we really need such cache, since IMO the array( ABigArray ) will be loaded in memory when trying to get one item. So we don't need use cache in such condition, right? Or I'm wrong?
如果我错了,请更正我。
Please correct me if I'm wrong.
谢谢。 >
Thanks.
推荐答案
你已经删掉了太多的信息,但它看起来像数组(实际上是字典)总是一样的 - 在模块首次导入时创建的单个实例,将由每个 Items
对象使用。所以缓存它绝对没有什么可以获得的 - 实际上你会失去这样做,因为你会引入不必要的往返行程来获取缓存中的数据。
You've cut out a bit too much information, but it looks like the "array" (actually a dictionary) is always the same - there's a single instance that is created when the module is first imported, and will be used by every Items
object. So there's absolutely nothing to be gained by caching it - in fact you will lose by doing so, as you will introduce an unnecessary round trip to get the data from the cache.
这篇关于我们需要缓存数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!