I am asking because I am trying to choose one for representing some data in my class and i want it to be space efficient.
I setup a small experiment and compared the sizes of the two datatypes at different sizes, on the range I plan to work on: 5-50 bytes, it seems that they are equal in size, only short by 1 byte. Only in the ranges of beyond 100 bytes does it seem to catch up and outcompete the integer datatype:
#๐ Is bytearray more space efficient than int?
22 messages ยท Page 1 of 1 (latest)
@green haven
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Closes after a period of inactivity, or when you send !close.
so the reasonable outcome would be that under 100 bytes, it doesn't really matter, whether one uses integer or a bytearray.
or?
a bytearray should be more efficient than a list of integers, but that should not matter for any practical use cases
-
if you are working with large amounts of data, use numpy instead of python built-in/standard library types
-
if you are working in an extremely restricted environment like micro controllers, use a low level language like C++ or Rust instead of Python
do you mean using a single very large integer vs a bytearray?
Internally (in CPython), an integer is an array of 30-bit digits. But each digit actually occupies 32 bits, so for very large numbers it should be about 7% less memory-efficient than bytearray
https://github.com/python/cpython/blob/2c451489122d539080c8d674b391dedc1dedcb53/Include/cpython/longintrepr.h#L64-L101
that is, if you're just using it to store bits and not do any arithmetic
(that said, if that sort of difference matters for your use case, then python may be the wrong tool for whatever your're doing)
The usual answer is: if it matters to you, measure it. If you don't want to measure, it doesn't matter enough ๐
than list of integers? i see, i was comparing to integer itself
thank you
made a plot, since i was curious:
left is difference in bytes
bottom is size in bytes
a lot of programs use 5-50 byte integers in a bunch of places... whether the small win in memory matters to you will depend on your particular program
i see, thanks
in my case it wouldn't really go beyond 50 nevertheless 100, so it should be okay
anyway, thanks, actually helped me a lot @nocturne onyx
!close
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.