You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: __slots__magic.rst
+48-2Lines changed: 48 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -19,7 +19,7 @@ of attributes. Here is an example with and without ``__slots__``:
19
19
.. code:: python
20
20
21
21
classMyClass(object):
22
-
def__init__(name, identifier):
22
+
def__init__(self, name, identifier):
23
23
self.name = name
24
24
self.identifier = identifier
25
25
self.set_up()
@@ -31,7 +31,7 @@ of attributes. Here is an example with and without ``__slots__``:
31
31
32
32
classMyClass(object):
33
33
__slots__= ['name', 'identifier']
34
-
def__init__(name, identifier):
34
+
def__init__(self, name, identifier):
35
35
self.name = name
36
36
self.identifier = identifier
37
37
self.set_up()
@@ -43,3 +43,49 @@ technique.
43
43
44
44
On a sidenote, you might want to give PyPy a try. It does all of these
45
45
optimizations by default.
46
+
47
+
48
+
Below you can see an example showing exact memory usage with and without ``__slots__`` done in IPython thanks to https://github.com/ianozsvald/ipython_memory_usage
49
+
50
+
.. code:: python
51
+
52
+
Python 3.4.3 (default, Jun 62015, 13:32:34)
53
+
Type "copyright", "credits"or"license"for more information.
54
+
55
+
IPython 4.0.0 -- An enhanced Interactive Python.
56
+
?-> Introduction and overview of IPython's features.
57
+
%quickref -> Quick reference.
58
+
help-> Python's own help system.
59
+
object?-> Details about 'object', use 'object??'for extra details.
60
+
61
+
In [1]: import ipython_memory_usage.ipython_memory_usage as imu
62
+
63
+
In [2]: imu.start_watching_memory()
64
+
In [2] used 0.0000 MiB RAMin5.31s, peaked 0.00 MiB above current, total RAM usage 15.57 MiB
65
+
66
+
In [3]: %cat slots.py
67
+
class MyClass(object):
68
+
__slots__ = ['name', 'identifier']
69
+
def__init__(self, name, identifier):
70
+
self.name = name
71
+
self.identifier = identifier
72
+
73
+
num = 1024*256
74
+
x = [MyClass(1,1) for i inrange(num)]
75
+
In [3] used 0.2305 MiB RAMin0.12s, peaked 0.00 MiB above current, total RAM usage 15.80 MiB
76
+
77
+
In [4]: from slots import*
78
+
In [4] used 9.3008 MiB RAMin0.72s, peaked 0.00 MiB above current, total RAM usage 25.10 MiB
79
+
80
+
In [5]: %cat noslots.py
81
+
classMyClass(object):
82
+
def__init__(self, name, identifier):
83
+
self.name = name
84
+
self.identifier = identifier
85
+
86
+
num =1024*256
87
+
x = [MyClass(1,1) for i inrange(num)]
88
+
In [5] used 0.1758 MiB RAMin0.12s, peaked 0.00 MiB above current, total RAM usage 25.28 MiB
89
+
90
+
In [6]: from noslots import*
91
+
In [6] used 22.6680 MiB RAMin0.80s, peaked 0.00 MiB above current, total RAM usage 47.95 MiB
0 commit comments