code-optimizer
Analyzes and optimizes code for better performance, memory usage, and efficiency. Use when code is slow, memory-intensive, or inefficient. Supports Python and Java optimization including execution speed improvements, memory reduction, database query optimization, and I/O efficiency. Provides before/after examples with detailed explanations of why optimizations work, complexity analysis, and measurable performance improvements.
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/code-optimizer && cp -r /tmp/code-optimizer/skills/code-optimizer ~/.claude/skills/code-optimizerSKILL.md
# Code Optimizer
Improve code performance, memory usage, and efficiency through systematic optimization.
## Core Capabilities
This skill helps optimize code by:
1. **Analyzing performance bottlenecks** - Identifying slow or inefficient code
2. **Suggesting optimizations** - Providing concrete improvements with examples
3. **Explaining trade-offs** - Describing benefits and potential drawbacks
4. **Measuring impact** - Estimating performance gains
5. **Preserving correctness** - Ensuring optimizations don't change behavior
## Optimization Workflow
### Step 1: Identify Optimization Opportunities
Analyze code to find performance bottlenecks.
**Look for:**
- Nested loops (O(n²) or worse complexity)
- Repeated expensive operations
- Inefficient data structures
- Unnecessary object creation
- Database N+1 queries
- Blocking I/O operations
- Memory leaks or excessive allocation
**Quick Analysis Questions:**
- What is the time complexity? Can it be reduced?
- Are there repeated calculations that could be cached?
- Is the right data structure being used?
- Are there unnecessary copies or allocations?
- Can operations be batched or parallelized?
### Step 2: Categorize the Optimization
Determine the type of optimization needed.
**Execution Speed:**
- Algorithm optimization (better complexity)
- Loop optimization
- Caching/memoization
- Lazy evaluation
- Parallel processing
**Memory Usage:**
- Reduce object creation
- Use generators/streams instead of lists
- Clear references to enable garbage collection
- Use appropriate data structures
- Avoid memory leaks
**Database Operations:**
- Query optimization (indexes, joins)
- Batch operations
- Connection pooling
- Caching
- Reduce round trips
**I/O Operations:**
- Buffering
- Async/non-blocking I/O
- Batch requests
- Compression
- Caching
### Step 3: Propose Optimization with Examples
Provide before/after code with clear explanations.
**Optimization Template:**
```markdown
## Optimization: [Brief Description]
### Before (Inefficient)
```[language]
[original code]
```
**Issues:**
- Issue 1: [Problem description]
- Issue 2: [Problem description]
**Complexity:** O([complexity])
**Performance:** [estimated time/memory]
### After (Optimized)
```[language]
[optimized code]
```
**Improvements:**
- Improvement 1: [What changed]
- Improvement 2: [What changed]
**Complexity:** O([new complexity])
**Performance:** [estimated time/memory]
**Gain:** [X% faster / Y% less memory]
### Why This Works
[Detailed explanation of the optimization]
### Trade-offs
**Pros:**
- [Benefit 1]
- [Benefit 2]
**Cons:**
- [Drawback 1, if any]
- [Drawback 2, if any]
### When to Use
- Use when: [scenario]
- Avoid when: [scenario]
```
### Step 4: Measure and Validate
Ensure optimization actually improves performance.
**Measurement Techniques:**
**Python:**
```python
import time
import memory_profiler
# Time measurement
start = time.time()
result = function()
elapsed = time.time() - start
print(f"Elapsed: {elapsed:.4f}s")
# Memory measurement
from memory_profiler import profile
@profile
def function():
# Code to profile
pass
```
**Java:**
```java
// Time measurement
long start = System.nanoTime();
result = function();
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed: " + elapsed / 1_000_000 + "ms");
// Memory measurement
Runtime runtime = Runtime.getRuntime();
long before = runtime.totalMemory() - runtime.freeMemory();
result = function();
long after = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Memory used: " + (after - before) / 1024 + "KB");
```
**Validation Checklist:**
- ✓ Correctness: Output matches original
- ✓ Performance: Measurable improvement
- ✓ Memory: Reduced allocation or leaks fixed
- ✓ Maintainability: Code remains readable
- ✓ Edge cases: Handles all inputs correctly
## Common Optimizations
### Python Optimizations
#### 1. Use List Comprehensions Over Loops
```python
# Before: O(n) with overhead
numbers = []
for i in range(1000):
if i % 2 == 0:
numbers.append(i * 2)
# After: O(n) faster execution
numbers = [i * 2 for i in range(1000) if i % 2 == 0]
# Gain: 2-3x faster
```
#### 2. Use Generators for Large Sequences
```python
# Before: O(n) memory
def get_numbers(n):
result = []
for i in range(n):
result.append(i ** 2)
return result
numbers = get_numbers(1000000) # Uses ~8MB memory
# After: O(1) memory
def get_numbers(n):
for i in range(n):
yield i ** 2
numbers = get_numbers(1000000) # Uses minimal memory
# Gain: 99% less memory for large n
```
#### 3. Use Built-in Functions
```python
# Before: Slower
total = 0
for num in numbers:
total += num
# After: Faster (C implementation)
total = sum(numbers)
# Gain: 10-20x faster for large lists
```
#### 4. Avoid Repeated Lookups
```python
# Before: Repeated lookups
for i in range(len(data)):
process(data[i])
# After: Single lookup
for item in data:
process(item)
# Or with enumerate
for i, item in enumerate(data):
process(item)
# Gain: Faster iteration, more Pythonic
```
#### 5. Use Sets for Membership Testing
```python
# Before: O(n) per lookup
items = [1, 2, 3, 4, 5, ...] # Large list
if x in items: # O(n) lookup
do_something()
# After: O(1) per lookup
items = {1, 2, 3, 4, 5, ...} # Set
if x in items: # O(1) lookup
do_something()
# Gain: 100x faster for large collections
```
See `references/python_optimizations.md` for comprehensive Python optimization patterns.
### Java Optimizations
#### 1. Use StringBuilder for String Concatenation
```java
// Before: O(n²) - creates n strings
String result = "";
for (int i = 0; i < 1000; i++) {
result += i + ","; // Creates new string each time
}
// After: O(n) - single buffer
StringBuilder result = new StringBuilder();
for (int i = 0; i < 1000; i++) {
result.append(i).append(",");
}
String output = result.toString();
// Gain: 100x faster for large loops
```
#### 2. Use Appropriate CollectApplies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.
Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.
Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.
Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.
Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.
CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.
Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.
Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.