0

I'm just wondering whether there is any difference in performance for accessing properties of a static instead of non-static class?

Let's say I have to classes

private class Book1
{
   public const EventEnum Name = "Something";
}

private static class Book2
{
   public const EventEnum Name = "Something";
}

Now, if I want to access them in the following way

var book1Name = Book1.Name;
var book2Name = Book2.Name;

is there an difference in performance? Is there any difference at all?

Thanks

Grentley
  • 315
  • 3
  • 6
  • 19
  • 6
    Don't try to learn millions of "performance rules" and then rigidly apply them. The best way to write good code is to first write *readable*, clearly *correct* code. Whilst doing that, also create performance *goals*. Once you've done that, **measure** your performance, and then target your efforts where your tools tell you you have a performance *issue*. – Damien_The_Unbeliever Dec 14 '16 at 13:05
  • [MeasureIt](https://measureitdotnet.codeplex.com/documentation) – rene Dec 14 '16 at 13:06
  • var book1Name = Book1.Name; Does that work if it's not static? – dahui Dec 14 '16 at 13:11
  • Those aren't properties, they're constants. And you can't mark a constant `static`, so this doesn't compile. Of course, that's incidental to your question, to which the answer is "you will have a very hard time ever finding an actual scenario where the answer to this is the least bit relevant, and if you do you will not get around measuring actual code anyway". See also [Eric Lippert's obligatory remarks on this](https://ericlippert.com/2012/12/17/performance-rant/). – Jeroen Mostert Dec 14 '16 at 13:11
  • 1
    _"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."_ – Rumen Georgiev Dec 14 '16 at 13:14
  • What if I don't mark these constants static, just the class itself? – Grentley Dec 14 '16 at 13:17
  • A constant cannot be marked as static, it *is* static – Bidou Dec 14 '16 at 13:19
  • 1
    I vote for reopening. The question is **not** a duplicate. OP asks the difference between static members of a non-static and a static class. The linked duplicate refers to static vs non-static **members**. The answer however should be the same – usr-local-ΕΨΗΕΛΩΝ Dec 14 '16 at 13:22
  • The OP is asking about properties, though mentioning constants. For *constants* at least, the answer is clear: there is zero difference because they're constants. All constants are inlined. For properties, the question is a duplicate because property getters are methods. – Jeroen Mostert Dec 14 '16 at 13:26
  • The code is using `const`, this will not behave the way you're expecting. The code will compile to exactly the same code which is basically just `var book1Name = "Something";` in both cases. – Lasse V. Karlsen Dec 14 '16 at 13:26
  • If the class is private, how does one access the properties? – Eris Dec 15 '16 at 06:14

0 Answers0