Last active
December 19, 2015 01:28
-
-
Save nvivo/5875718 to your computer and use it in GitHub Desktop.
Performance test for CA1813 - Avoid unsealed attributes http://msdn.microsoft.com/en-us/library/ms182267(v=vs.110).aspx
This file contains hidden or 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; | |
namespace AttributePerformanceTest | |
{ | |
public sealed class SealedAttribute : Attribute { } | |
public class NotSealedAttribute : Attribute { } | |
public class InheritNotSealedAttribute : NotSealedAttribute { } | |
public class ReInheritNotSealedAttribute : InheritNotSealedAttribute { } | |
[Sealed] | |
public class ClassWithSealed { } | |
[NotSealed] | |
public class ClassWithNotSealed { } | |
[InheritNotSealed] | |
public class ClassWithInherited { } | |
[ReInheritNotSealed] | |
public class ClassWithReInherited { } | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("*** Cold Run ***\r\n"); | |
Test(typeof(ClassWithSealed), typeof(SealedAttribute)); | |
Test(typeof(ClassWithNotSealed), typeof(NotSealedAttribute)); | |
Test(typeof(ClassWithInherited), typeof(NotSealedAttribute)); | |
Test(typeof(ClassWithReInherited), typeof(NotSealedAttribute)); | |
Console.WriteLine("\r\n*** Actual Test ***\r\n"); | |
Test(typeof(ClassWithSealed), typeof(SealedAttribute)); | |
Test(typeof(ClassWithNotSealed), typeof(NotSealedAttribute)); | |
Test(typeof(ClassWithInherited), typeof(NotSealedAttribute)); | |
Test(typeof(ClassWithReInherited), typeof(NotSealedAttribute)); | |
Console.WriteLine("\r\nDone"); | |
Console.ReadLine(); | |
} | |
static void Test(Type objectType, Type attributeType, int testRepeats = 5, int count = 100000) | |
{ | |
Console.WriteLine("Looking for {0} in {1}", attributeType.Name, objectType.Name); | |
long totalElapsed = 0; | |
for (int r = 0; r < testRepeats; r++) | |
{ | |
var sw = Stopwatch.StartNew(); | |
for (int i = 0; i < count; i++) | |
{ | |
Attribute.GetCustomAttributes(objectType, attributeType); | |
} | |
sw.Stop(); | |
totalElapsed += sw.ElapsedMilliseconds; | |
Console.Write(" {0} ms", sw.ElapsedMilliseconds); | |
} | |
Console.WriteLine("\r\nAverage: {0} ms\r\n", totalElapsed / testRepeats); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results on my machine: