performance-optimization.mdc•7.4 kB
---
description: SFCC performance optimization patterns and best practices
globs: ["**/*.js", "**/*.ts", "**/*.ds"]
alwaysApply: false
---
# SFCC Performance Optimization
Use this rule when optimizing SFCC application performance.
## Mandatory MCP Tools Sequence
**BEFORE optimizing ANY SFCC code:**
1. `mcp_sfcc-dev_search_best_practices` with query: "performance"
2. `mcp_sfcc-dev_get_best_practice_guide` with guideName: "performance"
3. `mcp_sfcc-dev_search_sfcc_classes` with query: relevant performance-critical domains
4. `mcp_sfcc-dev_get_latest_warn` - Check for performance warnings in logs
## MCP-Guided Performance Optimization Process
### Step 1: Get Performance Best Practices
```
Use: mcp_sfcc-dev_search_best_practices with query: "performance"
Use: mcp_sfcc-dev_get_best_practice_guide with guideName: "performance"
Purpose: Get comprehensive performance optimization strategies and patterns
```
### Step 2: Analyze Current Performance Issues
```
Use: mcp_sfcc-dev_get_latest_warn - Check for performance warnings
Use: mcp_sfcc-dev_search_logs with pattern: "timeout" or "slow"
Purpose: Identify current performance bottlenecks
```
### Step 3: Research Efficient SFCC APIs
```
Use: mcp_sfcc-dev_search_sfcc_classes with query: [performance-critical domain]
Use: mcp_sfcc-dev_get_sfcc_class_info with className: [performance-critical classes]
Purpose: Find most efficient SFCC APIs for your use case
```
## MCP-Enhanced Performance Patterns
### Efficient Database Queries (from MCP Performance Guide)
```javascript
// DON'T: Query in loops (anti-pattern from MCP performance guide)
products.forEach(function(productID) {
    var product = ProductMgr.getProduct(productID); // Multiple DB calls
});
// DO: Batch queries (pattern from MCP performance guide)
var ProductSearchModel = require('dw/catalog/ProductSearchModel');
var productSearchModel = new ProductSearchModel();
productSearchModel.setSearchPhrase(searchTerm);
productSearchModel.search();
var products = productSearchModel.getProductSearchHits(); // Use getProductSearchHits() instead of deprecated getProducts()
```
### Caching Strategies (from MCP Performance Guide)
```javascript
// Pattern from MCP performance best practices
var CacheMgr = require('dw/system/CacheMgr');
var cache = CacheMgr.getCache('custom-cache');
function getCachedData(key) {
    var cachedValue = cache.get(key);
    if (cachedValue) {
        return cachedValue;
    }
    // Expensive operation
    var data = performExpensiveOperation();
    cache.put(key, data, 3600); // Cache for 1 hour
    return data;
}
```
### Memory-Efficient Iterations (from MCP Performance Guide)
```javascript
// DON'T: Load all results into memory (anti-pattern from MCP)
var allProducts = ProductMgr.queryAllSiteProducts();
allProducts.toArray().forEach(function(product) {
    // Process product - causes memory issues
    // Note: toArray() loads all products into memory - avoid this pattern
});
// DO: Use iterators for large datasets (MCP performance pattern)
var productIterator = ProductMgr.queryAllSiteProducts();
try {
    while (productIterator.hasNext()) {
        var product = productIterator.next();
        // Process product efficiently
    }
} finally {
    productIterator.close(); // Critical: always close iterators
}
```
### Transaction Optimization (from MCP Performance Guide)
```javascript
// Pattern from MCP performance best practices
var Transaction = require('dw/system/Transaction');
// DON'T: Multiple small transactions
items.forEach(function(item) {
    Transaction.wrap(function() {
        item.save(); // Each iteration creates a transaction
    });
});
// DO: Batch operations in single transaction
Transaction.wrap(function() {
    items.forEach(function(item) {
        item.save(); // All operations in one transaction
    });
});
```
## Performance Checklist (MCP-Verified)
Before implementing performance optimizations, verify with MCP:
- [ ] `mcp_sfcc-dev_search_best_practices` with query: "performance" - Get optimization patterns
- [ ] `mcp_sfcc-dev_get_best_practice_guide` with guideName: "performance" - Comprehensive guide
- [ ] `mcp_sfcc-dev_get_latest_warn` - Check current performance warnings
Implementation checklist:
- [ ] Use caching for expensive operations
- [ ] Minimize database queries in loops
- [ ] Use iterators for large datasets and always close them
- [ ] Implement proper connection pooling
- [ ] Optimize template rendering with appropriate caching
- [ ] Use appropriate data structures
- [ ] Minimize object creation in loops
- [ ] Implement lazy loading where appropriate
- [ ] Use efficient search and sort algorithms
- [ ] Monitor and profile critical paths
## Common Performance Anti-Patterns (from MCP Performance Guide)
```javascript
// DON'T: Nested queries (anti-pattern from MCP)
categories.forEach(function(category) {
    var products = category.getProducts(); // Query per category
    products.forEach(function(product) {
        var inventory = product.getAvailabilityModel(); // Query per product
    });
});
// DO: Efficient data loading (pattern from MCP performance guide)
var CatalogMgr = require('dw/catalog/CatalogMgr');
var ProductSearchModel = require('dw/catalog/ProductSearchModel');
// Get categories efficiently using CatalogMgr
var siteCatalog = CatalogMgr.getSiteCatalog();
var categories = siteCatalog.getRoot().getSubCategories();
// Batch load products for all categories
var productSearchModel = new ProductSearchModel();
productSearchModel.setCategoryID(null); // Search across categories
productSearchModel.search();
var products = productSearchModel.getProductSearchHits(); // Use getProductSearchHits() instead of getProducts()
```
## MCP-Enhanced Template Performance
```javascript
// Template performance patterns from MCP ISML best practices
// Use appropriate caching headers
res.cachePeriod = 24; // Cache for 24 hours
res.cachePeriodUnit = 'hours';
// Minimize template includes in loops
var templateData = {
    products: products,
    // Pre-calculate expensive operations
    totalPrice: calculateTotalPrice(products),
    discountInfo: getDiscountInfo(products)
};
res.render('product/productList', templateData);
```
## Performance Monitoring with MCP Log Analysis
```javascript
// Add performance logging for MCP log analysis
var Logger = require('dw/system/Logger').getLogger('performance', 'ComponentName');
var startTime = Date.now();
try {
    // Performance-critical operation
    var result = performOperation();
    var duration = Date.now() - startTime;
    if (duration > 1000) { // Log slow operations
        Logger.warn('Slow operation detected: {0}ms - Operation: {1}', duration, 'operationName');
    } else {
        Logger.debug('Operation completed: {0}ms', duration);
    }
    return result;
} catch (e) {
    var duration = Date.now() - startTime;
    Logger.error('Operation failed after {0}ms: {1}', duration, e.message);
    throw e;
}
```
## NEVER Optimize Without MCP
- ❌ Don't guess at performance issues - use `mcp_sfcc-dev_get_latest_warn`
- ❌ Don't implement optimizations without patterns - use `mcp_sfcc-dev_get_best_practice_guide`
- ❌ Don't assume efficient APIs - use `mcp_sfcc-dev_search_sfcc_classes`
- ❌ Don't ignore memory management - follow MCP iterator closure patterns
- ❌ Don't skip transaction optimization - use MCP transaction batching patterns