How To Reduce Python Script Memory Usage

后端 未结 5 1083
庸人自扰
庸人自扰 2021-01-30 03:00

I have a very large python script, 200K, that I would like to use as little memory as possible. It looks something like:

# a lot of data structures
r = [34, 78,         


        
5条回答
  •  难免孤独
    2021-01-30 03:25

    If you're taking advantage of OOP and have some objects, say:

    class foo:
        def __init__(self, lorem, ipsum):
            self.lorem = lorem
            self.ipsum = ipsum
        # some happy little methods
    

    You can have the object take up less memory by putting in:

    __slots__ = ("lorem", "ipsum")
    

    right before the __init__ function, as shown:

    class foo:
        def __init__(self, lorem, ipsum):
            self.lorem = lorem
            self.ipsum = ipsum
        # some happy little methods
    

    Of course, "premature optimization is the root of all evil". Also profile mem usage before and after the addition to see if it actually does anything. Beware of breaking code (shcokingly) with the understanding that this might end up not working.

提交回复
热议问题