Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Challenge: Memory Optimization Audit | Performance Patterns
Python Memory Management
Avsnitt 4. Kapitel 5
single

single

Challenge: Memory Optimization Audit

Svep för att visa menyn

Uppgift

Svep för att börja koda

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"]
  1. Import sys and copy.
  2. Define a class PositionOptimized with __slots__ = ("position_id", "ticker", "quantity", "price") and the same __init__ as Position.
  3. Create an instance of Position called pos_original with values (1, "AAPL", 100, 189.50).
  4. Create an instance of PositionOptimized called pos_optimized with the same values.
  5. Store sys.getsizeof(pos_original) in size_original and sys.getsizeof(pos_optimized) in size_optimized.
  6. Create a shallow copy of pos_original.__dict__ called budget_copy using copy.copy().
  7. Print size_original, size_optimized, and budget_copy.

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 5
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt