Skip to content

パフォーマンス最適化サンプル

ここでは、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); // 1分ごとにクリア

アルゴリズム選択

適切なリサイズアルゴリズムの選択

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);
  // フォールバックを提供
}

関連リンク

Apache 2.0 ライセンスの下でリリースされています。