Примеры оптимизации производительности
Здесь представлены некоторые примеры оптимизации производительности Sharp и лучшие практики.
Оптимизация памяти
Потоковая обработка больших файлов
javascript
import sharp from 'sharp';
import fs from 'fs';
// Потоковая обработка, избегая загрузки всего файла в память
fs.createReadStream('large-image.jpg')
.pipe(sharp().resize(800, 600))
.pipe(fs.createWriteStream('output.jpg'));Использование Buffer вместо файла
javascript
// Для маленьких файлов использование Buffer более эффективно
const inputBuffer = fs.readFileSync('input.jpg');
const outputBuffer = await sharp(inputBuffer)
.resize(300, 200)
.jpeg({ quality: 80 })
.toBuffer();
fs.writeFileSync('output.jpg', outputBuffer);Своевременное освобождение ресурсов
javascript
// Своевременное освобождение после обработки
const image = sharp('input.jpg');
await image.resize(300, 200).toFile('output.jpg');
// Экземпляр image будет автоматически собран сборщиком мусораУправление параллелизмом
Ограничение количества параллельных операций
javascript
// Установка максимального количества параллельных операций
sharp.concurrency(4);
// Управление параллелизмом при пакетной обработке
async function batchProcess(files) {
const batchSize = 4;
const results = [];
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
const batchPromises = batch.map(file =>
sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`)
);
await Promise.all(batchPromises);
results.push(...batch);
}
return results;
}Использование очереди обработки
javascript
class ImageProcessor {
constructor(concurrency = 4) {
this.concurrency = concurrency;
this.queue = [];
this.running = 0;
}
async add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
this.process();
});
}
async process() {
if (this.running >= this.concurrency || this.queue.length === 0) {
return;
}
this.running++;
const { task, resolve, reject } = this.queue.shift();
try {
const result = await task();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.running--;
this.process();
}
}
}
// Пример использования
const processor = new ImageProcessor(4);
for (const file of files) {
processor.add(async () => {
await sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`);
});
}Оптимизация кэширования
Кэширование результатов обработки
javascript
const cache = new Map();
async function processWithCache(inputPath, width, height) {
const key = `${inputPath}_${width}_${height}`;
if (cache.has(key)) {
return cache.get(key);
}
const result = await sharp(inputPath)
.resize(width, height)
.jpeg({ quality: 80 })
.toBuffer();
cache.set(key, result);
return result;
}Очистка кэша Sharp
javascript
// Периодическая очистка кэша для освобождения памяти
setInterval(() => {
sharp.cache(false);
}, 60000); // Очистка каждую минутуВыбор алгоритма
Выбор подходящего алгоритма изменения размера
javascript
// Для уменьшения используем более быстрый алгоритм
await sharp('input.jpg')
.resize(300, 200, { kernel: sharp.kernel.cubic })
.toFile('output.jpg');
// Для увеличения используем более качественный алгоритм
await sharp('input.jpg')
.resize(1200, 800, { kernel: sharp.kernel.lanczos3 })
.toFile('output.jpg');Оптимизация пакетной обработки
javascript
async function optimizedBatchProcess(files) {
// Группировка по размеру для обработки
const smallFiles = [];
const largeFiles = [];
for (const file of files) {
const metadata = await sharp(file).metadata();
if (metadata.width * metadata.height < 1000000) {
smallFiles.push(file);
} else {
largeFiles.push(file);
}
}
// Маленькие файлы используют быстрый алгоритм
await Promise.all(smallFiles.map(file =>
sharp(file)
.resize(300, 200, { kernel: sharp.kernel.cubic })
.jpeg({ quality: 80 })
.toFile(`output_${file}`)
));
// Большие файлы используют качественный алгоритм
await Promise.all(largeFiles.map(file =>
sharp(file)
.resize(800, 600, { kernel: sharp.kernel.lanczos3 })
.jpeg({ quality: 90 })
.toFile(`output_${file}`)
));
}Оптимизация сети
Потоковый ответ
javascript
// Пример Express.js
app.get('/image/:filename', async (req, res) => {
const filename = req.params.filename;
try {
const imageStream = sharp(`images/${filename}`)
.resize(300, 200)
.jpeg({ quality: 80 });
res.set('Content-Type', 'image/jpeg');
imageStream.pipe(res);
} catch (error) {
res.status(404).send('Image not found');
}
});Условная обработка
javascript
app.get('/image/:filename', async (req, res) => {
const { filename } = req.params;
const { width, height, quality = 80 } = req.query;
try {
let image = sharp(`images/${filename}`);
if (width || height) {
image = image.resize(parseInt(width), parseInt(height));
}
if (req.headers.accept?.includes('image/webp')) {
image = image.webp({ quality: parseInt(quality) });
res.set('Content-Type', 'image/webp');
} else {
image = image.jpeg({ quality: parseInt(quality) });
res.set('Content-Type', 'image/jpeg');
}
image.pipe(res);
} catch (error) {
res.status(404).send('Image not found');
}
});Мониторинг и отладка
Мониторинг производительности
javascript
async function processWithTiming(inputPath, outputPath) {
const startTime = Date.now();
try {
await sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
const endTime = Date.now();
console.log(`Время обработки: ${endTime - startTime}ms`);
} catch (error) {
console.error('Обработка не удалась:', error.message);
}
}Мониторинг использования памяти
javascript
const process = require('process');
function logMemoryUsage() {
const usage = process.memoryUsage();
console.log('Использование памяти:', {
rss: `${Math.round(usage.rss / 1024 / 1024)} MB`,
heapTotal: `${Math.round(usage.heapTotal / 1024 / 1024)} MB`,
heapUsed: `${Math.round(usage.heapUsed / 1024 / 1024)} MB`,
external: `${Math.round(usage.external / 1024 / 1024)} MB`
});
}
// Запись использования памяти до и после обработки
logMemoryUsage();
await sharp('input.jpg').resize(800, 600).toFile('output.jpg');
logMemoryUsage();Обработка ошибок и повторные попытки
Механизм повторных попыток
javascript
async function processWithRetry(inputPath, outputPath, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
console.log(`Обработка успешна, количество попыток: ${attempt}`);
return;
} catch (error) {
console.error(`Попытка ${attempt} не удалась:`, error.message);
if (attempt === maxRetries) {
throw new Error(`Обработка не удалась, выполнено ${maxRetries} попыток`);
}
// Ожидание перед повторной попыткой
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}Классификация ошибок
javascript
async function robustProcess(inputPath, outputPath) {
try {
await sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
} catch (error) {
if (error.code === 'VipsForeignLoad') {
console.error('Неподдерживаемый формат изображения');
} else if (error.code === 'VipsForeignLoadLimit') {
console.error('Изображение слишком большое, попытка уменьшить');
// Попытка обработки уменьшенной версии
await sharp(inputPath, { limitInputPixels: 268402689 })
.resize(400, 300)
.jpeg({ quality: 80 })
.toFile(outputPath);
} else if (error.code === 'ENOSPC') {
console.error('Недостаточно места на диске');
} else {
console.error('Неизвестная ошибка:', error.message);
}
}
}Резюме лучших практик
1. Выбор подходящего способа обработки
javascript
// Маленькие файлы: прямая обработка
if (fileSize < 1024 * 1024) {
await sharp(file).resize(300, 200).toFile(output);
}
// Большие файлы: потоковая обработка
else {
fs.createReadStream(file)
.pipe(sharp().resize(300, 200))
.pipe(fs.createWriteStream(output));
}2. Оптимизация пакетной обработки
javascript
// Использование Promise.all для параллельной обработки
const promises = files.map(file =>
sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`)
);
await Promise.all(promises);3. Управление памятью
javascript
// Периодическая очистка кэша
setInterval(() => {
sharp.cache(false);
}, 300000); // Очистка каждые 5 минут4. Обработка ошибок
javascript
// Всегда используйте try-catch
try {
await sharp(input).resize(300, 200).toFile(output);
} catch (error) {
console.error('Обработка не удалась:', error.message);
// Предоставьте альтернативное решение
}