推荐学习书目
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 · 3792 views
    This topic created in 2849 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
        1
    BBCCBB  
       Jul 24, 2018
    string -> dict, 这还需要解释么?
    aice114
        2
    aice114  
       Jul 24, 2018 via Android
    用空间换时间嘛
    wwqgtxx
        3
    wwqgtxx  
       Jul 24, 2018   ❤️ 1
    有什么好奇怪的,数据结构不占用空间的么
    kunluanbudang
        4
    kunluanbudang  
       Jul 24, 2018 via Android
    如果了解 dict 的底层实现,几乎可以手动计算出来
    jameslan
        5
    jameslan  
       Jul 25, 2018 via Android
    @kunluanbudang 单层大 dict 和多层小 dict,内存占用差别还是很大的
    skiphuang
        6
    skiphuang  
    OP
       Jul 25, 2018
    @BBCCBB @aice114 @wwqgtxx @kunluanbudang @jameslan
    之前就知道字典需要额外的空间用于 hash,空间换时间,没太当回事,一看数据确实被惊到了
    而且确实这也是一个多层大字典

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

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