Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Memory Optimization Audit | Performance Patterns
Python Memory Management
Seksjon 4. Kapittel 5
single

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"]
  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 desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 5
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt