Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are some good methods to replace string names with integer hashes

Tags:

c++

string

Usually, entities and components or other parts of the game code in data-driven design will have names that get checked if you want to find out which object you're dealing with exactly.

void Player::Interact(Entity *myEntity)
{
    if(myEntity->isNearEnough(this) && myEntity->GetFamilyName() == "guard")
    {
       static_cast<Guard*>(myEntity)->Say("No mention of arrows and knees here");
    }
}

If you ignore the possibility that this might be premature optimization, it's pretty clear that looking up entities would be a lot faster if their "name" was a simple 32 bit value instead of an actual string.

Computing hashes out of the string names is one possible option. I haven't actually tried it, but with a range of 32bit and a good hashing function the risk of collision should be minimal.

The question is this: Obviously we need some way to convert in-code (or in some kind of external file) string-names to those integers, since the person working on these named objects will still want to refer to the object as "guard" instead of "0x2315f21a".

Assuming we're using C++ and want to replace all strings that appear in the code, can this even be achieved with language-built in features or do we have to build an external tool that manually looks through all files and exchanges the values?

like image 689
TravisG Avatar asked Jan 04 '12 16:01

TravisG


1 Answers

Jason Gregory wrote this on his book :

At Naughty Dog, we used a variant of the CRC-32 algorithm to hash our strings, and we didn't encounter a single collision in over two years of development on Uncharted: Drake's Fortune.

So you may want to look into that.

And about the build step you mentioned, he also talked about it. They basically encapsulate the strings that need to be hashed in something like:

_ID("string literal")

And use an external tool at build time to hash all the occurrences. This way you avoid any runtime costs.

like image 191
David Gouveia Avatar answered Oct 12 '22 13:10

David Gouveia