Python seems to use a lot of memory. So what exactly is the overhead of each type of value? Short answer:
int | 24 |
float | 24 |
tuple | 63 |
list | 101 |
dict | 298 |
old-style class | 345 |
new-style class | 336 |
subclassed tuple | 79 |
Record | 79 |
Record with old class mixin | 79 |
Record with new class mixin | 79 |
I measured these by running a simple program that loaded up 1,000,000 values in a list and then did time.sleep(1000). I ran that for different value types and then ran "top" to see how much memory was being used. I took that value, substracted the memory usage for a list of all the same value (14 bytes each), subtracted the value of a child value (usually an int, 24 bytes each), and then divided by 1,000,000. I'll include the code I ran at the end if you want to cut and paste. So what lessons do we learn from this?
- Python objects are very expensive at over 300 bytes each.
- Tuples have 1/5 as much overhead.
- Records are almost as good as tuples, even when a mixin is added.
So, if you want to have lots of values in memory without using lots of memory, use Record.
If you want to run the test for yourself, here's the code. Just comment out the "make_val" that you want to test.
import time from Record import Record class TupleClass(tuple): pass class RecordClass(Record("val")): pass class OldClass: def __init__(self, val): self.val = val def method(self): pass class NewClass(object): def __init__(self, val): self.val = val def method(self): pass class RecordWithOldClass(Record("val"), OldClass): pass class RecordWithNewClass(Record("val"), NewClass): pass make_val = lambda i : 1 #nothing (base overhead) #make_val = lambda i : i #make_val = float #make_val = lambda i : (i,) #make_val = lambda i : [i] #make_val = lambda i : {i:i} #make_val = TupleClass #make_val = RecordClass #make_val = OldClass #make_val = NewClass #make_val = RecordWithOldClass #make_val = RecordWithNewClass count = 1000000 lst = [make_val(i) for i in xrange(count)] time.sleep(100000)
Fun - I was just playing with the same sort of thing and came to a similar conclusion. One item that's useful is a slotted new style object:
ReplyDeleteclass Foo(object):
__slots__ = []
These come out to be (on average) slightly greater than 16 bytes / each.
If you add values:
class Foo(object):
__slots__ = ['a','b']
def __init__(self):
self.a = None
self.b = None
They come out to be ~65 bytes each.
Wow Gary! I tried that too and it came to about a quarter the size of virtual memory. This is way over my head but clearly indicates that __slots__ might be the way forward when memory matters.
ReplyDeleteIt would be interesting to see the exact same test run with a new-style class with __slots__ to eliminate the __dict__ attribute. According to your chart, the instance takes up 345 bytes, but the __dict__ should be taking up 298 of that; that that is eliminated when you use __slots__.
ReplyDeleteOops, I should have read the preceding comments before posting mine! Sorry.
ReplyDeleteI am getting wildly bigger values. Try this:
ReplyDelete#!/bin/sh
(
exec >test.py
echo "\
#!/usr/bin/python
import time"
i=300000
while test $i != 0; do
echo "i$i=$i"
: $((i--))
done
echo "time.sleep(3)"
)
chmod 755 test.py
echo "Before: `grep ^MemFree: /proc/meminfo`"
./test.py &
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
sleep 1
echo "During: `grep ^MemFree: /proc/meminfo`"
wait
echo "After: `grep ^MemFree: /proc/meminfo`"
# i=100000, output on my machine (x86-64):
#Before: MemFree: 308688 kB
#During: MemFree: 252144 kB
#During: MemFree: 227460 kB
#During: MemFree: 227468 kB
#During: MemFree: 227460 kB
#After: MemFree: 308200 kB
# Thus, (308200-227460)/100 = 807 bytes per each int variable
# i=300000
#Before: MemFree: 1007572 kB
#During: MemFree: 695952 kB
#During: MemFree: 421548 kB
#During: MemFree: 851084 kB
#During: MemFree: 835708 kB
#During: MemFree: 808800 kB
#During: MemFree: 795656 kB
#During: MemFree: 795656 kB
#During: MemFree: 795648 kB
#During: MemFree: 795656 kB
#After: MemFree: 1007448 kB
# Thus, (1007448-795648)/300 = 706 bytes per each int variable
I am a big fan of your blog.i am so excited by a read of your blog's content. great post.Thanks for sharing superb information.
ReplyDeleteProWeb365 Minneapolis web design
Mua vé máy bay tại Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ tháng nào rẻ nhất
giá vé máy bay từ mỹ về việt nam
vé máy bay từ canada về việt nam
vé máy bay từ hàn quốc về việt nam
ReplyDeleteThanks for sharing this informative content.,
Leanpitch provides online training in Scrum Master Certification during this lockdown period everyone can use it wisely.
Join Leanpitch 2 Days CSM Certification Workshop in different cities.
CSM online training
CSM training online
ReplyDeleteThanks for sharing this informative content.,
Leanpitch provides online training in Scrum Master Certification during this lockdown period everyone can use it wisely.
Join Leanpitch 2 Days CSM Certification Workshop in different cities.
CSM training online
Scrum master training online
Hey, Your blog is very informative. It is nice to read such high-quality content. Attractive information on your blog, thank you for taking the time and share with us. The experts of our Who can write my essay for me provide solution regarding paperhelp within the time that you provide us. Myassignmenthelp delivers high-quality content related to proposal essay topics and research paper help.
ReplyDeleteI love it when people get together and share views. Great site, Eunidrip company has wealth of experience in drilling boreholes.
ReplyDeleteAwesome article like your previous article Cheap Finance Assignment! I want people to know just how good this information is in your article. It’s interesting, compelling content. Your views are much like my own concerning this subject.
ReplyDeleteThank you for sharing this blog . your blog is very interesting and helpful. Quickbooks is a accounting software which is used in many organization to manage daily data. Quickbooks also available with many versions. Sometimes when Quickbooks's file get damage or corrupt it stops working. This error is called Quickbooks error 1334 . Due to this error all work get stuck.
ReplyDeleteran that for different value types and then ran top to see. Buy A Custom Essay took that value, substracted the memory usage for a list of all the same value.
ReplyDeleteThanks for sharing such a great blog Keep posting.
ReplyDeleteGreat article
ReplyDeletepaybyplate ma pay online
watch all episode of pinoy media pinoy tv and pinoy tambayan on our website
ReplyDeletehttps://krogerexperiencee
Nice Blog. QuickBooks Error 15241 is an error that prevents the QuickBooks Desktop software from successfully installing updates. It is connected to the QuickBooks Payroll feature. It's most likely caused by the QuickBooks Desktop software's File Copy Service being turned off.
ReplyDeleteI find all of this information fascinating, and it is full of useful information, so I'll be following your blog to learn new things.
ReplyDeleteHey thanks for this informative post, if you by any chance face QuickBooks Pro Error 1334 in your Quickbooks accounting software, any types of network issues or company file issues make sure to visit ebetterbooks.
ReplyDeleteWynn casino opens in Las Vegas - FilmfileEurope
ReplyDeleteWynn's first hotel casino in Las Vegas since opening its doors in 1996, 출장안마 Wynn Las Vegas febcasino is the first hotel on the Strip to https://septcasino.com/review/merit-casino/ offer such a large 토토 사이트 selection worrione of
virtual accounting firm provide their clients with real-time access to business accounting records by utilising Cloud Accounting software such as Xero. Indeed, platforms such as Xero enable virtual accountants and their clients to collaborate on their accounting records even if they are not in the same city, town, or state.
ReplyDeletevirtual accounting firm provide their clients with real-time access to business accounting records by utilising Cloud Accounting software such as Xero. Indeed, platforms such as Xero enable virtual accountants and their clients to collaborate on their accounting records even if they are not in the same city, town, or state.
ReplyDeleteI got many information in this blog keep share more useful information thanks. and we give best legal support for many people if anyone want it kindly visit our site thanks. reckless driving lawyer Henrico va
ReplyDelete
ReplyDeleteI recently completed my first scarf, and I couldn't be more proud of it! With each stitch, I felt a sense of accomplishment and creativity.
New Jersey Federal Criminal Lawyer
Federal Criminal Defense Lawyer
Motorcycle accident lawyers assist clients in navigating insurance claims, gathering evidence, and pursuing compensation for medical expenses, property damage, and other losses resulting from the accident. motorcycle accident lawyers
ReplyDeleteFascinating breakdown of Python memory usage! The insights into different value types and their overheads are invaluable. Thanks for sharing this detailed analysis and code snippet for testing
ReplyDeleteDriving Without A License In New Jersey
Python's memory usage can often be a mystery, especially when dealing with large datasets or complex algorithms. By delving into memory profiling, one can uncover valuable insights into which variables, data structures, or operations are consuming significant memory.
ReplyDeleteGreat read! Python's memory usage can indeed be perplexing, especially with large datasets or complex objects. It's crucial to identify and optimize the data structures and algorithms you use to manage memory efficiently. Speaking of optimizations, I recently came across a fantastic solution for those considering a mini tummy tuck Dubai - it's all about making the right choices for the best results!
ReplyDeleteGreat insights on Python memory management! Understanding which values consume the most memory is crucial for optimization. And let's not forget to appreciate Paul Rudd's effortless charm—always center stage!
ReplyDeleteGreat article! Python memory management can be tricky, but understanding memory usage is key to optimizing performance. It's a lot like choosing the right Villas in Dubai—you need to consider size, efficiency, and cost. Thanks for the insights!
ReplyDelete"Great analysis on Python memory usage! Understanding what's consuming resources is key to optimizing performance. For instance, in industries like HVAC, managing system efficiency is crucial. Similarly, if you're working on projects involving commercial evaporative cooling melbourne optimizing memory usage in your control systems or data analysis tools can significantly enhance operational efficiency and reduce costs. Would love to see more insights on profiling tools or techniques!"
ReplyDeleteNew York requires residency, follows equitable property division, and permits both fault-based and no-fault divorces. Based on parental and financial considerations, courts decide on child support, spousal support, and custody. Time and expense are impacted by whether a divorce is fought or not.
ReplyDeleteWhat are The Laws for Divorce in New York
There are many lessons to be learned in life, but the ones that really stick with us are the ones that influence our viewpoints and direct our behavior. Experiences, errors, mentors, and even unexpected obstacles can all teach us valuable lessons. We frequently learn resilience, empathy, patience, and the value of remaining true to who we are from these lessons. prostitution ring bust
ReplyDeleteBy promoting a culture of learning and self-reflection, the blog empowers individuals to make informed decisions, set meaningful goals, and lead more fulfilling lives. It is a go-to source for those seeking knowledge, inspiration, and guidance on their journey toward success. flsa lawyer nyc
ReplyDeleteEn Nueva Jersey, las personas afectadas por violencia doméstica tienen la posibilidad de pedir una orden de protección y obtener ayuda legal. Los delincuentes se enfrentan a responsabilidades legales, sanciones y posible reclusión. Hay albergues y recursos de soporte para asegurar la protección de las víctimas.
ReplyDeleteAyuda Violencia Doméstica Nueva Jersey
Your article is greatfull and thanks for sharing this article in my family. RPSC 2nd Grade Teacher Syllabus 2025 your article is very happy more aticle is share.Bihar CET BEd Apply Online 2025 : Check Application Dates, Exam Pattern & More Rajasthan Jail Prahari Answer Key 2025: राजस्थान जेल प्रहरी संभावित आंसर की जारी
ReplyDelete