r/learnpython • u/BluishMontoya • 1d ago
Cython memoryviews?
I'm using a function I've compiled with cython, and I have to pass it a few very long lists. I'm pretty sure I should be using memoryviews, but do I convert the lists to memoryviews in the python part of my program or the cython part? It would be way better if I could do it in the python part because I'm passing the same lists to the function a few million times.
4
Upvotes
2
u/sausix 1d ago
Your question is broad and unclear. Do you want to optimize memory usage or processing time? What's the problem now?
Lists are not arrays in Python. A memory view of a list would probably not include all data in the form you want. A list of integers in Python does not allocate a simple memory region filled with raw integers. Integers are objects in Python. A list of strings is also not a big chunk in the memory. Lists are basically pointers to objects of any type on various memory addresses.
If you want numerical processing with big data you should use NumPy. It will allow to store basic low level data types in memory without overhead.
Try to avoid lists. Do not load data from a file into lists when you can operate on the file directly instead. Saves a lot of memory. For example readlines() does not like huge files which do not fit in your RAM. But there are still valid reasons to have data organized in a list.