什么是一些好的方法用整数哈希替换字符串名称

编程入门 行业动态 更新时间:2024-10-12 20:24:04
本文介绍了什么是一些好的方法用整数哈希替换字符串名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

通常,数据驱动设计中的实体和组件或游戏代码的其他部分将具有名称,如果您想要确定您正在处理的对象是什么。

void Player :: Interact(Entity * myEntity) { if(myEntity-> isNearEnough(this)&& myEntity- > GetFamilyName()==guard) { static_cast< Guard *>(myEntity) - >说(没有提及箭头和膝盖 } }

如果忽略这可能是未成熟的优化,它很清楚,如果他们的名称是一个简单的32位值,而不是一个实际的字符串,查找实体将会快得多。

计算哈希字符串名称是一个可能的选项。我没有实际尝试过,但有一个32位的范围和良好的散列函数,碰撞的风险应该是最小的。

问题是这样的:显然,我们需要一些方法来将in-code(或某种外部文件)中的字符串名称转换为这些整数,对这些命名对象仍然希望将对象引用为guard而不是0x2315f21a。

假设我们使用C ++并想要替换所有字符串出现在代码中,这甚至可以通过语言构建的功能来实现,还是我们必须构建一个外部工具,手动查看所有文件并交换值?

解决方案

Jason Gregory在他的书:

在Naughty Dog中,我们使用CRC-32算法的变体来哈希我们的字符串,

因此,你可能想研究一下。 p>

关于你提到的构建步骤,他也谈到了。它们基本上封装了需要被哈希处理的字符串:

_ID(string literal)

并在构建时使用外部工具哈希所有出现。这样可以避免任何运行时成本。

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?

解决方案

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.

更多推荐

什么是一些好的方法用整数哈希替换字符串名称

本文发布于:2023-11-30 07:07:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   字符串   名称   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!