字符串池化解析:以Yosys IdString为例
c++ eda问题背景
在C++中,两个内容相同的字符串std::string是不同的对象:
1std::string s1 = "clk";
2std::string s2 = "clk";
3s1 == s2; // true,但O(n)逐字符比较
4&s1[0] != &s2[0]; // 不同内存地址
- 比较开销: O(n)逐字符比较
- 内存冗余: 相同字符串多份拷贝
- 哈希表性能: 重复计算哈希值
- 缓存不友好: 分散存储,cache miss
Yosys IdString的解决方案
IdString本质上是一个int
1struct IdString {
2 int index_; // 4字节ID代表字符串的身份
3
4 // O(1)比较
5 bool operator==(const IdString &rhs) const {
6 return index_ == rhs.index_;
7 }
8};
全局存储架构
1
2// 实际字符串存储
3static std …
