Introduction
Performance testing is essential for building high-quality applications. This article explores how to incorporate performance testing into your TDD workflow.
Response Time Testing
// performance.test.js
describe('API Performance', () => {
test('should respond within 100ms', async () => {
const start = performance.now();
await request(app).get('/api/users');
const duration = performance.now() - start;
expect(duration).toBeLessThan(100);
});
test('should handle concurrent requests', async () => {
const requests = Array(100).fill().map(() =>
request(app).get('/api/users')
);
const start = performance.now();
await Promise.all(requests);
const duration = performance.now() - start;
expect(duration).toBeLessThan(1000);
});
});
Memory Usage Testing
// memory.test.js
describe('Memory Usage', () => {
test('should not leak memory', async () => {
const initialMemory = process.memoryUsage().heapUsed;
for (let i = 0; i < 1000; i++) {
await processData(generateLargeDataset());
}
const finalMemory = process.memoryUsage().heapUsed;
const memoryIncrease = finalMemory - initialMemory;
expect(memoryIncrease).toBeLessThan(50 * 1024 * 1024); // 50MB
});
});
Database Performance
// database.test.js
describe('Database Performance', () => {
test('should execute query within 50ms', async () => {
const start = performance.now();
await db.query('SELECT * FROM users WHERE active = true');
const duration = performance.now() - start;
expect(duration).toBeLessThan(50);
});
test('should handle bulk operations', async () => {
const users = Array(1000).fill().map((_, i) => ({
name: `User ${i}`,
email: `user${i}@example.com`
}));
const start = performance.now();
await db.users.bulkCreate(users);
const duration = performance.now() - start;
expect(duration).toBeLessThan(1000);
});
});
Best Practices
- Set performance budgets
- Test under load
- Monitor memory usage
- Profile database queries
- Cache effectively
Conclusion
Performance testing should be an integral part of your TDD workflow. By following these practices, you can build faster and more efficient applications.
"Premature optimization is the root of all evil." - Donald Knuth
Member discussion: