こんにちは!TypeScriptやPythonの言語をメインに扱っているエンジニアのさわらと申します。
今回は、非同期タスクを並列処理することで、パフォーマンスに、どの程度、影響するのかが気になったので計測してみました。
複数の非同期APIリクエストを処理する想定でいきます。
利用させていただくのはみんな大好きJSONPlaceholderです。
無料プランだと大量のデータは扱えないと書かれてはいるのですが、具体的な記述がないので、今回は、とりあえず50件ほどフェッチしてパフォーマンスを計測してみたいと思います。
以下、公式サイトです。
https://my-json-server.typicode.com/
また言語はTypeScriptで実行環境は、TypeScript Playground(ブラウザ上の実行環境)となります。
実装を確認する
const fetchPost = async (id: number): Promise<any> => {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!response.ok) {
throw new Error(`Failed to fetch post with ID ${id}`);
}
const data = await response.json();
console.log(`Fetched post for ID ${id}`);
return data;
};
const sequentialFetch = async (ids: number[]): Promise<any[]> => {
const results: any[] = [];
console.time("Sequential Fetch"); // 時間計測開始
for (const id of ids) {
const result = await fetchPost(id); // 逐次処理
results.push(result);
}
console.timeEnd("Sequential Fetch"); // 時間計測終了
return results;
};
const parallelFetch = async (ids: number[], maxParallel: number): Promise<any[]> => {
const results: any[] = [];
console.time("Parallel Fetch"); // 時間計測開始
for (let i = 0; i < ids.length; i += maxParallel) {
const group = ids.slice(i, i + maxParallel);
const groupResults = await Promise.all(group.map((id) => fetchPost(id))); // 並列処理
results.push(...groupResults);
}
console.timeEnd("Parallel Fetch"); // 時間計測終了
return results;
};
// メイン実行
(async () => {
const ids = Array.from({ length: 50 }, (_, i) => i + 1);
const maxParallel = 5; // 最大並列数
console.log("\n=== Sequential Processing ===");
await sequentialFetch(ids);
console.log("\n=== Parallel Processing ===");
await parallelFetch(ids, maxParallel);
})();
パフォーマンスを計測してみる
順次処理
並列処理
結果
測定した結果、並列処理の方が約38.7分の1ほど処理時間が短縮できました。思ったより劇的に変わるという印象です。
並列処理では処理の順序が保証されない点に注意が必要なので、タスクの依存関係が強い場合は、工夫が必要そうですが、検討の価値は十分にあると感じました。
他にも、こんなパフォーマンス改善の手法があるよ!などありましたら気軽にコメントで教えていただけると嬉しいです!