How do empty Python strings use so much memory? #python #programming #coding #memory

preview_player
Показать описание
Empty python strings use a ton of memory - but why exactly is this? Subscribe & like for more python, programming, and coding content!

#python #programming #coding #pythonprogramming #computerscience #memory #pythontutorial #pythonforbeginners
Рекомендации по теме
Комментарии
Автор

Two things to note:
1) The memory measurement here is specific to Python 3.12 (CPython). Earlier version may use even more memory!
2) The C comparison uses 1 byte, since it's just the null-terminated character.

codeaffinitydev
Автор

A better comparison is with std::string in C++ or a String in Rust.

davidgillies
Автор

I'm confused. A character array is not a string. It's a pointer to character data. Why did you not include the size of the pointer?

codeman-dev
Автор

In C it's just a pointer to some memory, i.e. an array. And there is no length stored with it, so it's terminated by a \0 character. So an empty C string is 1 character, a \0 character.
While in python it stores more data along with it, probably a pointer, the length, and how much is allocated. Though maybe more.

Also, for C, since a pointer is 4 bytes (64 bits), it's technically 5 bytes. 4 to store the pointer, and 1 byte in memory storing the actual character \0

mrt_
Автор

Nice explanation 👍 but this begs the question, is the additional overhead worth it? It'd be interesting to see a comparison between C and Python running an equivalent program that processes string data.

ShortFilmVD
Автор

why does python string store all of that information by default? never intentionally used a string hash outside of a hashmap and even then it was calculated, not stored

wfufjpx
Автор

Can you please explain why a single character in string take 50bytes and and for integer it take 28bytes

Maniwin
Автор

Now i need to check how many bytes uses the string class i copied from an old graphics engine book(like 5years ago)

RaigyoEcU
Автор

The C string takes two bytes, one to store the string contents, one to store the pointer to the string.

TimothyWhiteheadzm
Автор

we can't compare C with python or any other language for that matter. Python runs on a virtual layer on top of the operating system. C was invented when Operating systems weren't a thing.

aravindmuthu