static class vs this?

Started by
21 comments, last by Hodgman 13 years ago

I'd expect a modern compiler to create the same code for both cases.

The only difference is that one is an evil global, and one isn't.


What makes you expect that? Just a random guess? Did you actually ever check the assembly generated?

I bet every time you call getInstance(), the compiler inserts an if() check to see if the singleton has been constructed yet, since it's a function-local static variable. That's a *lot* of extra runtime checks for something that will only branch once. If getInstance() gets inlined all over the place, that's a lot of extra code (in bytes), too.
Advertisement

[font="Courier New"][holywar][/font]
...Or just don't use globals, ever (nor singletons, which are just as evil).



P.S. there is no "[/holywar]" tag. good luck.


agree with this. They are a pain in the ass to debug and generally use more resources than you really need to. Loggers are usually ok, but using singletons opens the door to using more singletons, WHICH ARE BAD.

http://www.google.ca...lient=firefox-a

read and never do it again.

edit: the short reason to not use singletons is that they exhibit every bad characteristic about global objects except that they are less likely to cause namespace pollution.

[quote name='Hodgman' timestamp='1301549727' post='4792463']
I'd expect a modern compiler to create the same code for both cases.
What makes you expect that? Just a random guess? Did you actually ever check the assembly generated?

I bet every time you call getInstance(), the compiler inserts an if() check to see if the singleton has been constructed yet, since it's a function-local static variable. That's a *lot* of extra runtime checks for something that will only branch once. If getInstance() gets inlined all over the place, that's a lot of extra code (in bytes), too.
[/quote]Go back and look at the original post - I made that guess because the example specifically says "[color="#880000"][font="CourierNew, monospace"]no members[/font]", so the compiler won't need to go inserting branches in this particular case.

I also pointed out that the static/global version is less preferable ;)

This topic is closed to new replies.

Advertisement