Copying data is wasteful, mutating data is dangerous
You have a large chunk of data—a NumPy array, or a Pandas DataFrame—and you need to do a series of operations on it. By default both libraries make copies of the data, which means you’re using even more RAM. Both libraries do have APIs for modifying data in-place, but that can lead to other problems, including subtle bugs. So what can you do? In this article you’ll learn to recognize and apply the “hidden mutability” pattern, which offers a compromise between the two: the safe operation of copy-based APIs, with a somewhat reduced memory usage. Considering the following function: If you call that function with an array whose values range from 30 to 60, 30 will become 0.0, 45 will become 0.5, and 60 will become 1. How much memory does this function use? If the array uses A bytes, the function will use 3*A bytes of RAM: So how can we reduce memory usage? To reduce memory usage, you can use in-place operations like += to do those operations on the original array: Similarly: In all of these
Copying data is wasteful, mutating data is dangerous Copying data is wasteful, mutating data is dangerous by Itamar Turner-Trauring Last updated 12 Jan 2023, originally created 03 Jan 2020 You have a large chunk of data—a NumPy array, or a Pandas DataFrame—and you need to do a series of operations on it. By default both libraries make copies of the data, which means you’re using even more RAM. Both libraries do have APIs for modifying data in-place, but that can lead to other problems, including subtle bugs. So what can you do? In this article you’ll learn to recognize and apply the “hidden mu
related reading
- Making Deep Learning go Brrrr From First Principleshorace.io
- Using PyTorch + NumPy? You're making a mistake. · Tanel Pärnamaatanelp.github.io
- Write code that is easy to delete, not easy to... — programming is terribleprogrammingisterrible.com
- abseil / Performance Hintsabseil.io
- Python's Array: Working With Numeric Data Efficiently – Real Pythonrealpython.com
- Time complexity of operations on built-in typesdocs.python.org
- Starting out with Numpy, Pandas, Scikit-Learn, and Kerasblog.sdan.net
- Emulating pass-by-value behaviour in Python - Stack Overflowstackoverflow.com
- 12 Tidy data | Python for Data Sciencebyuidatascience.github.io
- Variables and Mutability - The Rust Programming Languagedoc.rust-lang.org
- Memory location matters for performancepythonspeed.com
- Immutability in React: Should you mutate objects? - LogRocket Blogblog.logrocket.com