Seksjon 4. Kapittel 5
single
Challenge: Memory Optimization Audit
Sveip for å vise menyen
Oppgave
Sveip for å begynne å kode
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.
Løsning
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 4. Kapittel 5
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår