Do we need cache for an array?

旧城冷巷雨未停 提交于 2019-12-24 19:23:14

问题


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.

the code sample like this:

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/1680349/do-we-need-cache-for-an-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!