V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
skiphuang
V2EX  ›  Python

python2 字符串转字典之后 内存的变化让我吓一跳!!!

  •  
  •   skiphuang · 2018-07-24 18:07:37 +08:00 · 3104 次点击
    这是一个创建于 2102 天前的主题,其中的信息可能已经有所发展或是发生改变。

    项目里遇到这么一行代码如下:

    dict_data = eval(str_data)
    

    str_data 大小在 3MB 左右,用 memory_profiler 检测到在这一行内存却增加了 50MB 左右,为何?

    有没有大佬给个提示

    6 条回复    2018-07-25 08:34:18 +08:00
    BBCCBB
        1
    BBCCBB  
       2018-07-24 18:20:02 +08:00
    string -> dict, 这还需要解释么?
    aice114
        2
    aice114  
       2018-07-24 18:25:19 +08:00 via Android
    用空间换时间嘛
    wwqgtxx
        3
    wwqgtxx  
       2018-07-24 18:26:39 +08:00   ❤️ 1
    有什么好奇怪的,数据结构不占用空间的么
    kunluanbudang
        4
    kunluanbudang  
       2018-07-24 18:49:39 +08:00 via Android
    如果了解 dict 的底层实现,几乎可以手动计算出来
    jameslan
        5
    jameslan  
       2018-07-25 07:11:52 +08:00 via Android
    @kunluanbudang 单层大 dict 和多层小 dict,内存占用差别还是很大的
    skiphuang
        6
    skiphuang  
    OP
       2018-07-25 08:34:18 +08:00
    @BBCCBB @aice114 @wwqgtxx @kunluanbudang @jameslan
    之前就知道字典需要额外的空间用于 hash,空间换时间,没太当回事,一看数据确实被惊到了
    而且确实这也是一个多层大字典

    现在项目里面因为这个问题,导致内存吃的很严重
    正在努力找优化的切入点

    背景:
    做转换的原因是需要处理`str_data`数据,用于生产 protocol buffers
    大佬们,有想法可以指点一二吗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   982 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:07 · PVG 05:07 · LAX 14:07 · JFK 17:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.