I read somewhere that having public properties is preferable to having public members in a class.
Is this only because of abstaraction and modularity? Are there any other over-riding reasons?
The property accesses are conerted into function calls by the compiler. For properties without a backup store (e.g. public string UserName { get; set; }
), what would be the performance overhead compared to a direct member access? (I know it shouldn't usually make a difference but in some of my code, properties are accessed millions of times.)
Edit1: I ran some test code over integer members and Properties and the public members were about 3-4 times as fast as Properties. (~57 ms. vs ~206 ms. in Debug and 57 vs. 97 in Release was the most common run value). For 10 million reads and writes, both are small enough not to justify changing anything.
Code:
class TestTime1 { public TestTime1() { } public int id=0; } class TestTime2 { public TestTime2() { } [DefaultValue(0)] public int ID { get; set; } } class Program { static void Main(string[] args) { try { TestTime1 time1 = new TestTime1(); TestTime2 time2 = new TestTime2(); Stopwatch watch1 = new Stopwatch(); Stopwatch watch2 = new Stopwatch(); watch2.Start(); for (int i = 0; i < 10000000; i++) { time2.ID = i; i = time2.ID; } watch2.Stop(); watch1.Start(); for (int i = 0; i < 10000000; i++) { time1.id = i; i = time1.id; } watch1.Stop(); Console.WriteLine("Time for 1 and 2 : {0},{1}",watch1.ElapsedMilliseconds,watch2.ElapsedMilliseconds); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.In.ReadLine(); } }
Running the test 20 times in a row, ensuring that JIT optimization is enabled in the Release build:
Time for 1 and 2 : 47,66 Time for 1 and 2 : 37,42 Time for 1 and 2 : 25,36 Time for 1 and 2 : 25,25 Time for 1 and 2 : 27,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 26,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25 Time for 1 and 2 : 25,25
Yes, the JITter is that good at inlining property accessors. Perf is a non-issue and should never be considered.
Don't worry at all about the performance overhead. It is so minor that you should not consider weakening the encapsulation of the class; it would be premature optimization of the worst sort.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With