Home Backend Development Python Tutorial Python object memory usage

Python object memory usage

Feb 28, 2017 pm 04:48 PM

Everything is an object

Everything in Python is an object, including all types of constants and variables, integers, Boolean types, and even functions. See a question on stackoverflow Is everything an object in python like ruby

You can verify it in the code:

# everythin in python is object def fuction(): return print isinstance(True, object ) print isinstance(0, object) print isinstance('a', object) print isinstance(fuction, object)

How to calculate

Python provides the function getsizeof in the sys module to calculate Python objects the size of.

sys.getsizeof(object[, default])

以字节(byte)为单位返回对象大小。 这个对象可以是任何类型的对象。 所以内置对象都能返回正确的结果 但不保证对第三方扩展有效,因为和具体实现相关。

......

getsizeof() 调用对象的 __sizeof__ 方法, 如果对象由垃圾收集器管理, 则会加上额外的垃圾收集器开销。
Copy after login

Of course, the object memory usage is closely related to the Python version and operating system version. The code and test results in this article are based on the windows7 32-bit operating system.

import sys print sys.version

2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)]

Basic type

•Boolean

print 'size of True: %d' % (sys.getsizeof(True)) print 'size of False: %d' % (sys.getsizeof (False))

Output:

size of True: 12 size of False: 12

•Integer

# normal integer print 'size of integer: %d' % (sys.getsizeof(1)) # long print 'size of long integer: %d' % (sys.getsizeof(1L)) print 'size of big long integer: %d' % (sys. getsizeof(100000L)) Output:

size of integer: 12x size of long integer 1L: 14 size of long integer 100000L: 16

It can be seen that the integer occupies 12 bytes, and the long integer The type occupies at least 14 bytes, and the space occupied will become larger as the number of bits increases. In version 2.x, if the value of the integer type exceeds sys.maxint, it is automatically expanded to a long integer. After Python 3.0, integers and long integers are unified into one type.

•Floating point type

print 'size of float: %d' % (sys.getsizeof(1.0))

Output:

size of float: 16

Floating point type occupies 16 bytes. Exceeding a certain precision will be rounded off.

Refer to the following code:

print 1.00000000003 print 1.000000000005

Output:

1.00000000003 1.00000000001

•String

# size of string type print '\r\n'.join(["size of string with %d chars: %d" % (len(elem), sys.getsizeof(elem)) for elem in [ "", "a", "ab"]]) # size of unicode string print '\r\n'.join(["size of unicode string with %d chars: %d" % (len(elem), sys .getsizeof(elem)) for elem in [u"", u"a", u"ab"]])

Output:

size of string with 0 chars: 21 size of string with 1 chars: 22 size of string with 2 chars: 23 size of unicode string with 0 chars: 26 size of unicode string with 1 chars: 28 size of unicode string with 2 chars: 30

Normal null character The string occupies 21 bytes, and each additional character occupies 1 more byte. Unicode strings occupy a minimum of 26 bytes, and each additional character occupies an additional 2 bytes.

Collection type

•List

# size of list type print '\r\n'.join(["size of list with %d elements: %d" % (len(elem), sys.getsizeof(elem)) for elem in [[], [0], [0,2], [0,1,2]]])

Output:

size of list with 0 elements: 36 size of list with 1 elements: 40 size of list with 2 elements: 44 size of list with 3 elements: 48

The visible list occupies the least 36 bytes, each additional element adds 4 bytes. But be aware that the sys.getsizeof function does not calculate the element size of the container type. For example:

print 'size of list with 3 integers %d' % (sys.getsizeof([0,1,2])) print 'size of list with 3 strings %d' % (sys.getsizeof (['0','1','2']))

Output:

size of list with 3 integers 48 size of list with 3 strings 48

What is stored in the container should be a reference to the element. If you want to accurately calculate the container, you can refer to the recursive sizeof recipe. Use the total_size function given by it:

print 'total size of list with 3 integers %d' % (total_size([0,1,2])) print 'total size of list with 3 strings %d ' % (total_size(['0','1','2']))

The output is:

total size of list with 3 integers 84 total size of list with 3 strings 114

It can be seen that the space occupied by the list is basic space 36 + (object reference 4 + object size) * number of elements.

Also note that if you declare a list variable, it will pre-allocate some space to increase efficiency when adding elements:

li = [] for i in range(0, 101) : print 'list with %d integers size: %d, total_size: %d' % (i, getsizeof(li), total_size(li)) li.append(i)

•Tuple

Basically similar to a list, but it occupies at least 28 bytes.

•Dictionary

The situation of dictionaries is relatively complicated. Of course, you should refer to the code dictobject.c for details. In addition, NOTES ON OPTIMIZING DICTIONARIES is worth reading carefully.

For the basic situation, you can refer to some answers in [stackoverflow] question Python's underlying hash data structure for dictionaries:

•The dictionary has a minimum space of 8 entries (PyDict_MINSIZE);
•When the number of entries is less than 50,000, it will grow 4 times each time;
•When the number of entries is greater than 50,000, it will grow 2 times each time;
•The hash value of the key is cached in the dictionary and will not be recalculated after the dictionary is resized;

The dictionary will be resized every time it approaches 2/3.

The above article on Python object memory usage is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more articles related to Python object memory usage, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles