What you should know Whenever you see STL containers or strings.

We all know that stl is great. It has fantastic daily-used data structures, algorithms and string. We’ve learned that we should use it instead of array or char*. Yeah, it enables us to avoid reinventing the wheel! and save lots of lots of time.

So what’s the problem?

It’s allocating memory.

It does NOT mean stl sucks because it needs heap memory. There is no problem as long as we know what we’re doing. It’s allocating memory when you use them and this could be an issue when you find your program is not fast enough and the reason for that is memory fragmentation, you know enough memory space but fragmented as hell.

For example, (This is bad. never do this.)

void Render()
    osringstream strFPS;
    strFPS << "FPS : " << GetFPS();

Now, I’m sure you see the problem. It will create countless small temporary memories and definitely affect overall memory usage. I know some of you use your own “new/delete” or “malloc/free” but that doesn’t make big difference since it’s going to make your memory pool fragmented and you need time for de-fragmenting to find enough space.

So what should we do?

Well, here are my own tips.

1. Try to reuse stl objects as much as possible.
– Put them into a class as member variables.
– “static” can be one solution if you are free from threads.
– Always “reserve” their space in advance to avoid unnecessary allocations.

2. For temporary local objects, try to use “stack” objects, not heap ones.
– Use array if you know the maximum size.
– Try boost::array if you really don’t like to see brackets.
– stl::string is too tempting but for temporary strings, char[] can be much more efficient.

That’s it.

I think this is my last post for 2009. I was reading my old posts last night and I really like them. lol. I sometimes learn many things from what I’ve written. In 2010 (oh wow! cannot believe I will live in 2010!), hope I will be a slightly better programmer than now.

Merry Christmas and Happy New Year!


About 리안 / Young

글쓰는 게임 프로그래머. 남편 그리고 아빠. Game Programmer Writing. A husband and a father.
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to What you should know Whenever you see STL containers or strings.

  1. iluzdaf says:

    I learn much from your posts too…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s