Section 4. Chapter 5
single
Challenge: Memory Optimization Audit
Swipe to show menu
Task
Swipe to start coding
You are auditing a data model used in a financial reporting system. Your task is to apply the memory optimization techniques from this section to reduce the footprint of the Position class and verify the improvements with sys.getsizeof().
You are given the following starting class and dataset:
class Position:
def __init__(self, position_id, ticker, quantity, price):
self.position_id = position_id
self.ticker = ticker
self.quantity = quantity
self.price = price
tickers = ["AAPL", "MSFT", "GOOG", "AMZN", "TSLA"]
- Import
sysandcopy. - Define a class
PositionOptimizedwith__slots__ = ("position_id", "ticker", "quantity", "price")and the same__init__asPosition. - Create an instance of
Positioncalledpos_originalwith values(1, "AAPL", 100, 189.50). - Create an instance of
PositionOptimizedcalledpos_optimizedwith the same values. - Store
sys.getsizeof(pos_original)insize_originalandsys.getsizeof(pos_optimized)insize_optimized. - Create a shallow copy of
pos_original.__dict__calledbudget_copyusingcopy.copy(). - Print
size_original,size_optimized, andbudget_copy.
Solution
Everything was clear?
Thanks for your feedback!
Section 4. Chapter 5
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat