class LoopOptimizer: @staticmethod def optimize_list_comprehension(data): return [x ** 2 for x in data if x > 0] @staticmethod def optimize_generator(data): return (x ** 2 for x in data if x > 0) @staticmethod def optimize_map_filter(data): return map(lambda x: x ** 2, filter(lambda x: x > 0, data)) def slow_loop(items): result = [] for item in items: if item % 2 == 0: result.append(item * 2) return result def optimized_loop(items): return [item * 2 for item in items if item % 2 == 0] def vectorized_operation(arr): import numpy as np return arr[arr % 2 == 0] * 2
2.2 字符串优化
class StringOptimizer: @staticmethod def slow_concat(items): result = "" for item in items: result += str(item) return result @staticmethod def fast_concat(items): return "".join(str(item) for item in items) @staticmethod def format_string(data): return f"Name: {data['name']}, Age: {data['age']}" @staticmethod def template_string(data): from string import Template template = Template("Name: ${name}, Age: ${age}") return template.substitute(data) def build_query(params): query_parts = [] if 'name' in params: query_parts.append(f"name = '{params['name']}'") if 'age' in params: query_parts.append(f"age = {params['age']}") return " AND ".join(query_parts)
2.3 缓存优化
from functools import lru_cache class CacheOptimizer: def __init__(self, maxsize=128): self.cache = {} self.maxsize = maxsize def memoize(self, func): def wrapper(*args): if args not in self.cache: if len(self.cache) >= self.maxsize: self.cache.pop(next(iter(self.cache))) self.cache[args] = func(*args) return self.cache[args] return wrapper @lru_cache(maxsize=128) def compute_fibonacci(n): if n < 2: return n return compute_fibonacci(n - 1) + compute_fibonacci(n - 2) class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = {} self.order = [] def get(self, key): if key in self.cache: self.order.remove(key) self.order.append(key) return self.cache[key] return None def put(self, key, value): if key in self.cache: self.order.remove(key) elif len(self.cache) >= self.capacity: oldest = self.order.pop(0) del self.cache[oldest] self.cache[key] = value self.order.append(key)
class OptimizationChecker: @staticmethod def check(code): issues = [] if 'for ' in code and 'result.append' in code: issues.append("考虑使用列表推导代替for循环") if 'result += ' in code: issues.append("考虑使用str.join代替字符串拼接") if 'def ' in code and 'return ' in code: issues.append("考虑使用lru_cache缓存函数结果") return issues