推荐学习书目
› 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 · Jul 24, 2018 · 4252 views
    This topic created in 3029 days ago, the information mentioned may be changed or developed.

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

    dict_data = eval(str_data)
    

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

    有没有大佬给个提示

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

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

    背景:
    做转换的原因是需要处理`str_data`数据,用于生产 protocol buffers
    大佬们,有想法可以指点一二吗
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4567 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 02:44 · PVG 10:44 · LAX 18:44 · JFK 21:44
    ♥ Do have faith in what you're doing.