動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

定石4:性能比較— Stopwatch + GC.GetTotalMemory

出典: C# ファイルIO の正解 — StreamReader / File.ReadAllLines / File.ReadLines / using の使い分け定石4:性能比較— Stopwatch + GC.GetTotalMemory

定石4:性能比較— Stopwatch + GC.GetTotalMemory (csharp)#976121387821
// ✅定石4:性能比較(10万行×約100MBのログを想定)
const string path = @"C:\logs\big-app.log";
 
// ReadAllLines版(メモリに全部ロード)
GC.Collect(); GC.WaitForPendingFinalizers();
long memBefore = GC.GetTotalMemory(true);
var sw1 = Stopwatch.StartNew();
 
string[] all = File.ReadAllLines(path, Encoding.UTF8);
int errCnt1 = all.Count(l => l.Contains("ERROR"));
 
sw1.Stop();
long memAfter = GC.GetTotalMemory(false);
Console.WriteLine($"ReadAllLines: {sw1.ElapsedMilliseconds}ms / {(memAfter - memBefore)/ 1024 / 1024}MB / {errCnt1}件");
 
// ReadLines版(ストリーム読み込み)
GC.Collect(); GC.WaitForPendingFinalizers();
memBefore = GC.GetTotalMemory(true);
var sw2 = Stopwatch.StartNew();
 
int errCnt2 = File.ReadLines(path, Encoding.UTF8).Count(l => l.Contains("ERROR"));
 
sw2.Stop();
memAfter = GC.GetTotalMemory(false);
Console.WriteLine($"ReadLines   : {sw2.ElapsedMilliseconds}ms / {(memAfter - memBefore)/ 1024 / 1024}MB / {errCnt2}件");
▸ 実行ボタンで結果を表示
  • id: #976121387821
  • lines: 25
  • extracted: 2026-06-10
  • captured: 2026-06-04

Source収録記事

この snippet は記事の「定石4:性能比較— Stopwatch + GC.GetTotalMemory」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

5
図鑑トップ