POC Performance Optimization 2 — Questions and Answers
Question 1: Which Python built-in function returns an iterator over a range of numbers without creating a list in memory?
- list()
- range() (Correct answer)
- enumerate()
- map()
Correct answer: range()
range() in Python 3 returns a lazy iterator that generates numbers on demand, avoiding memory allocation for the full sequence.
Question 2: What is the primary advantage of using `array` module over a list for numeric data in Python?
- Faster string operations
- Lower memory usage due to typed storage (Correct answer)
- Built-in sorting algorithms
- Thread-safe operations
Correct answer: Lower memory usage due to typed storage
The array module stores elements as typed C values, consuming significantly less memory than Python lists which store object references.
Question 3: Which caching strategy does `functools.lru_cache` implement?
- First-In First-Out (FIFO)
- Least Recently Used (LRU) (Correct answer)
- Most Recently Used (MRU)
- Random Replacement
Correct answer: Least Recently Used (LRU)
lru_cache evicts the least recently used entries when the cache reaches its maximum size, keeping frequently accessed results.
Question 4: What does the `__slots__` class attribute do in Python?
- Enables multiple inheritance
- Replaces the instance __dict__ to reduce memory overhead (Correct answer)
- Defines abstract methods
- Creates class-level constants
Correct answer: Replaces the instance __dict__ to reduce memory overhead
__slots__ eliminates the per-instance __dict__, reducing memory usage significantly when creating many instances of a class.
Question 5: Which of the following is the fastest way to concatenate many strings in Python?
- Using += in a loop
- Using str.format()
- Using ''.join(list_of_strings) (Correct answer)
- Using f-strings in a loop
Correct answer: Using ''.join(list_of_strings)
''.join() is O(n) because it allocates one buffer for all strings, while += in a loop creates a new string object on every iteration.
Question 6: What is the time complexity of checking membership in a Python set compared to a list?
- O(n) for both
- O(1) for set, O(n) for list (Correct answer)
- O(log n) for set, O(n) for list
- O(n) for set, O(1) for list
Correct answer: O(1) for set, O(n) for list
Sets use a hash table internally, giving O(1) average-case membership testing, whereas lists require O(n) linear scan.
Question 7: What does the `timeit` module measure in Python?
- Memory usage of functions
- Execution time of small code snippets (Correct answer)
- CPU core utilization
- Network latency
Correct answer: Execution time of small code snippets
timeit runs a code snippet many times and returns the best elapsed wall-clock time, minimizing measurement noise for micro-benchmarks.
Which Python built-in function returns an iterator over a range of numbers without creating a list in memory?