Skip to content

Instantly share code, notes, and snippets.

@pierre3
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pierre3/10731634 to your computer and use it in GitHub Desktop.
Save pierre3/10731634 to your computer and use it in GitHub Desktop.
C# メソッドをasyncにする、しないのパフォーマンス比較
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Test().Wait();
Console.Read();
}
static async Task Test()
{
var text = string.Join(Environment.NewLine, Enumerable.Range(1, 100000).Select(_ => Guid.NewGuid()));
using (var reader = new TextReaderWrapper(new StringReader(text)))
{
while (null != await reader.ReadLineAsync()) ;
}
for (int i = 0; i < 10; i++)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
using (var reader = new TextReaderWrapper(new StringReader(text)))
{
while (null != await reader.ReadLineAsync()) ;
}
sw.Stop();
Console.Write(sw.ElapsedMilliseconds + ", ");
sw.Restart();
using (var reader = new TextReaderWrapper(new StringReader(text)))
{
while (null != await reader.ReadLineAsync2()) ;
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
class TextReaderWrapper : IDisposable
{
TextReader reader;
public TextReaderWrapper(TextReader reader)
{
this.reader = reader;
}
public Task<string> ReadLineAsync()
{
return this.reader.ReadLineAsync();
}
public async Task<string> ReadLineAsync2()
{
return await this.reader.ReadLineAsync();
}
public void Dispose()
{
if (this.reader == null) return;
this.reader.Dispose();
}
}
}
}
10万行のテキストをTextReader.ReadLineAsync() をラップしたメソッドで読み取り、実行時間を計測した結果
asyncなし, あり (単位 ms)
--------------
9, 20
8, 19
9, 19
9, 19
9, 19
8, 20
9, 19
8, 19
8, 19
9, 19
-------------
8.6, 19.2 (10回平均)
//asyncなし
public Task<string> ReadLineAsync()
{
return this.reader.ReadLineAsync();
}
//asyncあり
public async Task<string> ReadLineAsync2()
{
return await this.reader.ReadLineAsync();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment