• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
nuclear123

static class vs this?

22 posts in this topic

is there a difference/overhead in doing this....

[code]
class Log
{
private: // no members
public:
void createLog( );
};

int main()
{

Log log1;
log1.createLog();

}[/code]

[code]


class Log
{
private: // no members
public:
static void createLog( );
};


int main()
{
Log::createLog();
}
[/code]

is this the same exact code? or does the non static one create useless overhead and is bad code/slower
0

Share this post


Link to post
Share on other sites
No, they are not the same.

A static member function does not operate on an object.
A non-static member function must have an object, which is automatically passed to the function as the [i]this[/i] pointer.

The performance difference between the two is very nearly nothing.


Generally you use a static member function when you want a function to be part of a class interface but you won't actually reference a part of the object. For example, you may use it to look up common values.

I'm guessing that eventually createLog is going to modify the state of a Log object, so it shouldn't be a static function.
1

Share this post


Link to post
Share on other sites
If you want Log to be available with the same instance everywhere, think about using a Singleton.

[code]
class Log : public boost::noncopyable
{
private:
Log()
{}

public:
static Log& getInstance()
{
static Log OnlyOne;
return OnlyOne;
}

void createLog()
{
// .....
}

void logIt(int, string&)
{}
};

#define LOGERROR(s) Log::getInstance().logIt(L_ERROR, s)

int main()
{
Log::getInstance().createLog();
LOGERROR("I am feeling depressed.");
}
[/code]

Static Values can also be used to define Strings or things used over the whole program:
[code]
class Math
{
static double PI;
};

double Math::PI = 3.14159265;

int main()
{
using namespace std;
cout << "PI is exactly: " << Math::PI << endl;
}
[/code]
-3

Share this post


Link to post
Share on other sites
[quote name='NicoG' timestamp='1301513209' post='4792295']
If you want Log to be available with the same instance everywhere, think about using a Singleton. [/quote]
Why not just use a global?
0

Share this post


Link to post
Share on other sites
If logging is your bottleneck then you are doing it wrong. In any case with logging the slow part is usually the I/O, not the function calls themselves. Don't micro optimise unless you have a performance problem and you have exhausted macro optimisations.
1

Share this post


Link to post
Share on other sites
[quote name='jyk' timestamp='1301548655' post='4792461']
[quote name='NicoG' timestamp='1301513209' post='4792295']
If you want Log to be available with the same instance everywhere, think about using a Singleton. [/quote]
Why not just use a global?
[/quote]

Of course could he use a global, but in my eyes a singleton provides a cleaner access-interface.
0

Share this post


Link to post
Share on other sites
I believe a Singleton provides a worse interface. It tends to be more verbose, and it is harder to create sub-system local log instances. For example, you might want to set the log verbosity of your graphics subsystem to high, while keeping others low. For low complexity games, I'd probably just use simple procedure calls rather than create a class at all. Any state can be kept in an anonymous namespace.

Or just use std::cout, std::cerr and std::clog directly. I might modify their rdbuf() to output to a in-game console or to a file, or I might use OS-level pipes to capture the output to a file.
1

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1301569120' post='4792528']
I believe a Singleton provides a worse interface. It tends to be more verbose, and it is harder to create sub-system local log instances. For example, you might want to set the log verbosity of your graphics subsystem to high, while keeping others low. For low complexity games, I'd probably just use simple procedure calls rather than create a class at all. Any state can be kept in an anonymous namespace.

Or just use std::cout, std::cerr and std::clog directly. I might modify their rdbuf() to output to a in-game console or to a file, or I might use OS-level pipes to capture the output to a file.
[/quote]

When you use a singleton, it is guaranteed that you cannot access the singleton before it is created. Hence getInstance().
You don't have that guarantee with static globals.

I use such a logging singleton for creating html logs. You can represent debugging data much better with that when you are unable to pause the process because it depends on timing etc, which is esp. the case when you are doing games. Well, at least it is an easy method to achieve this.
I made myself a class log and logwriter. logwriter can be derived and output any format such as csv, text or html.
0

Share this post


Link to post
Share on other sites
[quote name='NicoG' timestamp='1301569795' post='4792530']
When you use a singleton, it is guaranteed that you cannot access the singleton before it is created. Hence getInstance().
You don't have that guarantee with static globals.[/quote]
How about something like (not compiled or tested):

[code]// In a header file somewhere:
Log& GetLog();

// In a source file:
Log& GetLog()
{
static Log log;
return log;
}[/code]
In this case the instance will be created the first time it's accessed, just like with your 'get instance' method, correct? Assuming that's correct and I'm not overlooking anything, what advantages does the singleton method have over something like the above?
0

Share this post


Link to post
Share on other sites
Uhm, what you are doing has only 1 difference to a singleton:
The get-function is not a member of the class. That would be unintuitive for me.
With global normally one means rather this:

[code]
Log g_log;

int main()
{
g_log.doSomething();
}
[/code]

And thats not advised for the reasons above. Of course, in 1 source file it does not matter at all. But if you have a complex project, Singletons are the way to go over global Objects. In my Opinion. :)

edit: One must be careful not to create too many singletons. Using it too much and too often can lead to bad design. Experienced this myself.
0

Share this post


Link to post
Share on other sites
[quote name='NicoG' timestamp='1301570431' post='4792535']
Uhm, what you are doing has only 1 difference to a singleton: [/quote]
Are you sure? With the method I posted above, I can create additional loggers wherever and whenever needed. So that's at least [i]two[/i] differences, and it's a pretty significant difference at that ;)

[quote]Singletons are the way to go over global Objects.[/quote]
But why?
0

Share this post


Link to post
Share on other sites
Well, yes okay, you are free to have more loggers than 1 and you are not restricting the class. Thats right, my bad.
But that isn't a global object then by definition.
In fact, I use it like this, but I have one singleton in my App which offers a "systemwide" logbook.
http://code.google.com/p/nightlight2d/source/browse/trunk/NightLightDLL/NLSystemController.hpp


[quote]
But why?
[/quote]

If you have globals and meaning real globals, not static functions, it is not guaranteed that global1 in compilation unit 1 is created before global2 in compilation unit 2 is accessing it.
At least to my knowledge of the c++ standard in this case. Also, a global always uses the memory it needs, a singleton only if it is used at all.
0

Share this post


Link to post
Share on other sites
[quote]
When you use a singleton, it is guaranteed that you cannot access the singleton before it is created. Hence getInstance(). [/quote]
I have only a handful of globals, all of which are totally independent of one another. A global logger, sometimes, a global resource cache (does nothing on construction) and rarely anything else. I've used the trick jyk showed before for managing the resource cache, in my newer code bases I simply don't make it global.

[quote]
If you have globals and meaning real globals, not static functions...[/quote]
We mean a value that is globally accessible (somehow).

[quote]
...it is not guaranteed that global1 in compilation unit 1 is created before global2 in compilation unit 2 is accessing it.
At least to my knowledge of the c++ standard in this case. Also, a global always uses the memory it needs, a singleton only if it is used at all.[/quote]
There are also potential multi-threaded issues with the delayed initialisation of global values. I tend not to worry about the memory usage, as the few globals I have are pretty much always used, unless the program shuts down because the configuration is completely corrupt.
0

Share this post


Link to post
Share on other sites
[font="arial, verdana, tahoma, sans-serif"][size="2"]Yes, the 'static initialization order fiasco' is certainly something to be aware of, but the method shown in my example above shouldn't be susceptible to that. Also, it doesn't suffer from the (usually artificial) limitation that there be only one, and it requires less support code than a singleton. Granted, the difference in complexity is minimal, but I don't see any particular reason to make things more complex than they would be otherwise, just so you can impose a constraint that probably isn't needed anyway.[/size][/font]
0

Share this post


Link to post
Share on other sites
May I just throw this out there? Multiton? although I think we drifted far away from the question which I think was much more basic.
0

Share this post


Link to post
Share on other sites
Here's a radical idea: have you considered not making a class at all?

I'm pretty sure people used to do logging in the pre-Stroustrup era. I'm also pretty sure that the normal approach to logging in C did not involve the 'struct' keyword.
0

Share this post


Link to post
Share on other sites
Don't use singletons - ffs, don't waste time writing logs, use an off the shelf.
-1

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1301549727' post='4792463']
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.
[/quote]

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.
0

Share this post


Link to post
Share on other sites
[quote name='Hodgman' timestamp='1301573694' post='4792554']
[font="Courier New"][holywar][/font]
...Or just don't use globals, ever (nor singletons, which are just as evil).



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

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.

[url="http://www.google.ca/search?q=singletons+are+bad&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a"]http://www.google.ca...lient=firefox-a[/url]

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.
0

Share this post


Link to post
Share on other sites
[quote name='RDragon1' timestamp='1301639263' post='4792906']
[quote name='Hodgman' timestamp='1301549727' post='4792463']
I'd expect a modern compiler to create the same code for both cases.[/quote]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"][size="2"]no members[/size][/font][/color]", 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 ;)
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0