Note that there are some explanatory texts on larger screens.

plurals
  1. POPerformance overhead for properties in .NET
    primarykey
    data
    text
    <p>I read somewhere that having public properties is preferable to having public members in a class. </p> <ol> <li><p>Is this only because of abstaraction and modularity? Are there any other over-riding reasons?</p></li> <li><p>The property accesses are conerted into function calls by the compiler. For properties without a backup store (e.g. <code>public string UserName { get; set; }</code>), 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.)</p></li> </ol> <p>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.</p> <p>Code:</p> <pre><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 &lt; 10000000; i++) { time2.ID = i; i = time2.ID; } watch2.Stop(); watch1.Start(); for (int i = 0; i &lt; 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(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload