Created
March 14, 2014 10:28
-
-
Save munyabe/9545371 to your computer and use it in GitHub Desktop.
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.Diagnostics; | |
using System.Linq; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace Test | |
{ | |
[TestClass] | |
public class PerformanceTest | |
{ | |
[TestMethod] | |
public void ForLoopPerformanceTest() | |
{ | |
var array = Enumerable.Range(0, 10000000).ToArray(); | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
var result = CreateArrayByFor(array); | |
//var result = CreateArrayByForeach(array); | |
//var result = CreateArrayByLinq(array); | |
stopwatch.Stop(); | |
var ms = stopwatch.ElapsedMilliseconds; | |
} | |
private int[] CreateArrayByFor(int[] source) | |
{ | |
var result = new int[source.Length]; | |
for (int i = 0; i < result.Length; i++) | |
{ | |
result[i] = source[i] * 10; | |
} | |
return result; | |
} | |
private int[] CreateArrayByForeach(int[] source) | |
{ | |
var result = new int[source.Length]; | |
int index = 0; | |
foreach (var each in source) | |
{ | |
result[index++] = each * 10; | |
} | |
return result; | |
} | |
private int[] CreateArrayByLinq(int[] source) | |
{ | |
return source.Select(x => x * 10).ToArray(); | |
} | |
[TestMethod] | |
public void ListForEachTest() | |
{ | |
var list = Enumerable.Range(0, 10000000).ToList(); | |
var array = new int[list.Count]; | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
//for (int i = 0; i < list.Count; i++) | |
//{ | |
// array[i] = list[i]; | |
//} | |
var index = 0; | |
list.ForEach(each => | |
{ | |
array[index] = each; | |
index++; | |
}); | |
stopwatch.Stop(); | |
var ms = stopwatch.ElapsedMilliseconds; | |
} | |
[TestMethod] | |
public void EnumGetHashCodeTest() | |
{ | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
for (int i = 0; i < 1000000; i++) | |
{ | |
//var test = (int)Hoge.Foo.GetHashCode(); | |
var test = ((int)Hoge.Foo).GetHashCode(); | |
} | |
stopwatch.Stop(); | |
var ms = stopwatch.ElapsedMilliseconds; | |
} | |
// MEMO : http://stackoverflow.com/questions/7368652/what-is-it-that-makes-enum-hasflag-so-slow | |
[TestMethod] | |
public void EnumHasFlagTest() | |
{ | |
var stopwatch = new Stopwatch(); | |
stopwatch.Start(); | |
var flags = Fuga.A | Fuga.C; | |
for (int i = 0; i < 10000000; i++) | |
{ | |
//var test = flags.HasFlag(Fuga.B); | |
var test = (flags & Fuga.B) != 0; | |
} | |
stopwatch.Stop(); | |
var ms = stopwatch.ElapsedMilliseconds; | |
} | |
private enum Hoge | |
{ | |
Foo | |
} | |
[Flags] | |
public enum Fuga | |
{ | |
A = 1, | |
B = 2, | |
C = 4, | |
D = 8 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment