Vector Efficiency question

Started by
12 comments, last by Shannon Barber 9 years, 9 months ago

If you're iterating over all members, a vector is as fast as it gets. If you want to be able to lookup by id, a sorted vector is pretty fast too.

Advertisement

If you must have string-lookups, then use std::unordered_map. By using std::unordered_map, you are saying, "I don't care whether you preserve the order I add elements to the map, you can store them however you want, just make them as fast as possible."

However, string comparisons are (relatively) slow. If you're only gonna have 10000 or so entities, it'd probably be fine, but strings have other problems: How do you handle case sensitivity? std::strings, and thus also strings in maps, are case-sensitive by default, so "Bob" is not the same as "bob" or "BOB". You can normalize your names before using them to look up elements, but then that's another issue of unnecessary slowness. Also, what if there is more than one enemy named "skeleton" - you'll have to detect that, and then create "skeleton_01", "skeleton_02", and so on. For what purpose?

If you want better efficiency, use consecutive integer keys (e.g. 0, 1, 2, 3, etc...) with std::vector, doing myVector[index].

When you add an entity, do something like this:


typedef size_t EntityID;

EntityID MyClass::AddEntity(const Entity &entity)
{
    EntityID entityID = myVector.size();
    myVector.push_back(entity);

    return entityID;
}

Then you can go:


EntityID entityID = myClass.AddEntity(Entity(stuff));

And you save your entityID for later lookups for things like collisions and so on.

What Servant of the Lord said. The only reason to have strings in such a data structure is for debugging purposes.

So the string comparisons are relatively slow?

You would have to get very creative to find a slower way.

Perhaps you load a data file into a vector (or map) with string names, but then you would process that data into trees of data using pointers.

- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement