Created
October 20, 2011 20:20
-
-
Save kamranayub/1302236 to your computer and use it in GitHub Desktop.
Performance of reading AppSetting via different backing methods
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; | |
namespace PerfBackingFields | |
{ | |
class Program | |
{ | |
private const int Iterations = 100000; | |
static void Main(string[] args) | |
{ | |
Stopwatch timer = new Stopwatch(); | |
var testClass = new TestClass(); | |
// | |
// Static backing field via read only property | |
// | |
Console.WriteLine("Static backing field via read only property:"); | |
timer.Start(); | |
for (var i = 0; i < Iterations; i++) | |
{ | |
var s = testClass.ConfigValue1; | |
} | |
timer.Stop(); | |
Console.WriteLine("\tElapsed: " + timer.Elapsed.ToString()); | |
// | |
// Read only property | |
// | |
Console.WriteLine("Read only property:"); | |
timer.Restart(); | |
for (var i = 0; i < Iterations; i++) | |
{ | |
var s = testClass.ConfigValue1_RO; | |
} | |
timer.Stop(); | |
Console.WriteLine("\tElapsed: " + timer.Elapsed.ToString()); | |
// | |
// Static read only property | |
// | |
Console.WriteLine("Static read only property:"); | |
timer.Restart(); | |
for (var i = 0; i < Iterations; i++) | |
{ | |
var s = TestClass.ConfigValue1_ROS; | |
} | |
timer.Stop(); | |
Console.WriteLine("\tElapsed: " + timer.Elapsed.ToString()); | |
// | |
// Static readonly field | |
// | |
Console.WriteLine("Static readonly field:"); | |
timer.Restart(); | |
for (var i = 0; i < Iterations; i++) | |
{ | |
var s = TestClass.ConfigValue1_Static; | |
} | |
timer.Stop(); | |
Console.WriteLine("\tElapsed: " + timer.Elapsed.ToString()); | |
Console.ReadKey(); | |
} | |
} | |
class TestClass | |
{ | |
private static string _configValue1; | |
public string ConfigValue1 | |
{ | |
get | |
{ | |
if (string.IsNullOrEmpty(_configValue1)) | |
_configValue1 = System.Configuration.ConfigurationManager.AppSettings["ConfigValue1"]; | |
return _configValue1; | |
} | |
} | |
public string ConfigValue1_RO | |
{ | |
get | |
{ | |
return System.Configuration.ConfigurationManager.AppSettings["ConfigValue1"]; | |
} | |
} | |
public static string ConfigValue1_ROS | |
{ | |
get | |
{ | |
return System.Configuration.ConfigurationManager.AppSettings["ConfigValue1"]; | |
} | |
} | |
public static readonly string ConfigValue1_Static = System.Configuration.ConfigurationManager.AppSettings["ConfigValue1"]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment