Friday, November 20, 2009

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

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, [BAD one, never do this.]

void Render()
{
string fps = string("FPS : ") + GetFPS();
DrawText(fps);
}

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 postings 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!