Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsCommunityBlog
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Optimizing Code

ASecurity

Improve code performance without changing behavior. Use when code fails latency/throughput requirements. Covers profiling, caching, and algorithmic optimization.

34 stars
0 votes
0 copies
0 views
Added 9/22/2026
businessgojavabashspringdatabaseperformance

Security Analysis

A96/100
mediumUses curl or wget to download content

Scanned 9/22/2026

Install to Claude Code

$npx -y skills add nguyenhuuca/assessment --skill optimizing-code --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Optimizing Code?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Optimizing Code
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/nguyenhuuca-optimizing-code/badge)](https://www.skillsdirectory.com/skills/nguyenhuuca-optimizing-code)

More formats (shields.io, HTML) on the badges page.

Download with Pro
Files
SKILL.md
---
name: optimizing-code
description: Improve code performance without changing behavior. Use when code fails latency/throughput requirements. Covers profiling, caching, and algorithmic optimization.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# Optimizing Code

## The Optimization Hat

When optimizing, you improve **performance** without changing **behavior**. Always measure before and after.

## Golden Rules

1. **Measure First**: Never optimize without a benchmark
2. **Profile Before Guessing**: Find the actual bottleneck
3. **Optimize the Right Thing**: Focus on the critical path
4. **Measure After**: Verify the optimization worked

## Workflows

- [ ] **Benchmark**: Establish baseline performance metrics
- [ ] **Profile**: Identify the actual bottleneck
- [ ] **Hypothesize**: What optimization will help?
- [ ] **Implement**: Make the change
- [ ] **Measure**: Verify improvement
- [ ] **Document**: Record the optimization and results

## Common Optimizations

### Algorithm Complexity
- Replace O(n²) with O(n log n) or O(n)
- Use appropriate data structures (Set for lookups, Map for key-value)

### Caching (Java + Guava)
```java
// In-memory caching with Guava
@Service
public class DataService {
    private final LoadingCache<String, Result> cache;

    public DataService() {
        this.cache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Result>() {
                @Override
                public Result load(String key) {
                    return expensiveCalculation(key);
                }
            });
    }

    public Result getData(String input) {
        return cache.getUnchecked(input);
    }

    private Result expensiveCalculation(String input) {
        // Expensive work here
        return new Result();
    }
}
```

### Virtual Threads (Java 24)
```java
// Leverage Virtual Threads for I/O-heavy operations
@Configuration
public class VirtualThreadConfig {
    @Bean
    public TomcatProtocolHandlerCustomizer<?> protocolHandlerVirtualThreadExecutor() {
        return protocolHandler -> {
            protocolHandler.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
        };
    }
}

// Parallel processing with StructuredTaskScope
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Future<UserDto> user = scope.fork(() -> fetchUser(userId));
    Future<List<Order>> orders = scope.fork(() -> fetchOrders(userId));

    scope.join();
    scope.throwIfFailed();

    return buildProfile(user.resultNow(), orders.resultNow());
}
```

### Database Queries (JPA/Hibernate)
```java
// ❌ BAD: N+1 query problem
@GetMapping("/users")
public List<UserDto> getUsers() {
    List<User> users = userRepository.findAll();
    // This triggers N additional queries!
    return users.stream()
        .map(user -> new UserDto(user, user.getOrders()))
        .toList();
}

// ✅ GOOD: Use JOIN FETCH to load in one query
@Query("SELECT u FROM User u LEFT JOIN FETCH u.orders WHERE u.status = :status")
Page<User> findActiveUsersWithOrders(@Param("status") UserStatus status, Pageable pageable);

// ✅ GOOD: Use @EntityGraph for eager loading
@EntityGraph(attributePaths = {"orders", "profile"})
List<User> findByStatus(UserStatus status);

// ✅ GOOD: Pagination for large result sets
@GetMapping("/users")
public Page<UserDto> getUsers(
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "20") int size
) {
    Pageable pageable = PageRequest.of(page, size);
    return userService.findAll(pageable);
}
```

- Add indexes for frequently queried columns
- Avoid N+1 queries (use JOIN FETCH or @EntityGraph)
- Use pagination for large result sets
- Use read-only transactions for queries: `@Transactional(readOnly = true)`

### Memory
- Avoid creating unnecessary objects in loops
- Use streaming for large files
- Release references when done

## Profiling Tools

```bash
# Java/JVM Profiling
# 1. JProfiler (commercial)
# 2. VisualVM (free, included with JDK)
jvisualvm

# 3. Async Profiler (open-source, production-ready)
java -agentpath:/path/to/libasyncProfiler.so=start,event=cpu,file=profile.html -jar app.jar

# 4. Spring Boot Actuator + Micrometer
# Add to application.yaml:
# management.endpoints.web.exposure.include=metrics,health
# management.metrics.export.prometheus.enabled=true

# View metrics
curl http://localhost:8081/actuator/metrics

# 5. JMH (Java Microbenchmark Harness) for method-level benchmarking
mvn exec:java -Dexec.mainClass=org.openjdk.jmh.Main

# 6. Heap dump analysis
jmap -dump:format=b,file=heap.bin <pid>
jhat heap.bin

# 7. Thread dump
jstack <pid> > threads.txt

# 8. GC logging
java -Xlog:gc*:file=gc.log -jar app.jar
```

## Anti-Patterns to Avoid

- Premature optimization (no benchmark)
- Micro-optimizations (negligible impact)
- Optimizing cold paths
- Sacrificing readability for minor gains

Attribution

nguyenhuucanguyenhuuca
View sourceMore from nguyenhuuca →
SSkills DirectorySkills Directory

Know which skills are safe — weekly.

Best new skills + every skill we flagged as malicious. From the team that scanned 103,619.

Join free

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Know which skills are safe — weekly.

Best new skills + every skill we flagged as malicious. From the team that scanned 103,619.

Join free

Related Skills

Solution Architect

Designs system architecture, component specifications, and technical integration strategy. Use when: designing solutions, system architecture, technology stack, or integration approaches.

192 votes

Akorchak:Venture Assessment

Generate a comprehensive VC investment assessment report for a company

72 votes

Telegram Compose

Compose rich, readable Telegram messages using HTML formatting via direct Telegram API. Use when: (1) Sending any Telegram message beyond a simple one-line reply, (2) Creating structured messages with sections, lists, or status updates, (3) Need formatting unavailable via Clawdbot's Markdown conversion (underline, spoilers, expandable blockquotes, user mentions by ID), (4) Sending alerts, reports, summaries, or notifications to Telegram, (5) Want professional, scannable message formatting wit...

6511 votes

Stock Analysis

Analyze stocks and cryptocurrencies using Yahoo Finance data. Supports portfolio management (create, add, remove assets), crypto analysis (Top 20 by market cap), and periodic performance reports (daily/weekly/monthly/quarterly/yearly). 8 analysis dimensions for stocks, 3 for crypto. Use for stock analysis, portfolio tracking, earnings reactions, or crypto monitoring.

6511 votes

Just Fucking Cancel

Find and cancel unwanted subscriptions by analyzing bank transactions. Detects recurring charges, calculates annual waste, and helps you cancel with direct URLs and browser automation. Use when: 'cancel subscriptions', 'audit subscriptions', 'find recurring charges', 'what am I paying for', 'save money', 'subscription cleanup', 'stop wasting money'. Supports CSV import (Apple Card, Chase, Amex, Citi, Bank of America, Capital One, Mint, Copilot) OR Plaid API for automatic transaction pull. Out...

6511 votes
View all in business →