Skip to content

Instantly share code, notes, and snippets.

@nvivo
Last active December 19, 2015 01:28
Show Gist options
  • Save nvivo/5875718 to your computer and use it in GitHub Desktop.
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
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);
}
}
}
@nvivo
Copy link
Author

nvivo commented Jun 27, 2013

Results on my machine:

Looking for SealedAttribute in ClassWithSealed
  447 ms  449 ms  445 ms  450 ms  450 ms
Average: 448 ms

Looking for NotSealedAttribute in ClassWithNotSealed
  430 ms  424 ms  429 ms  433 ms  443 ms
Average: 431 ms

Looking for NotSealedAttribute in ClassWithInherited
  452 ms  429 ms  428 ms  435 ms  440 ms
Average: 436 ms

Looking for NotSealedAttribute in ClassWithReInherited
  440 ms  433 ms  441 ms  437 ms  433 ms
Average: 436 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment