Last active
August 29, 2015 13:59
-
-
Save pierre3/10731634 to your computer and use it in GitHub Desktop.
C# メソッドをasyncにする、しないのパフォーマンス比較
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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