c++ - C++ 中 "rich type"结构的开销

标签 c++ optimization struct compile-time overhead

我想在编译时跟踪一些当前采用相同类型参数的函数的基本“类型”信息。这是一个例子;假设我有两个函数 getThingIndex(uint64_t t)getThingAtIndex(uint64_t tidx)。第一个函数将参数视为 thing 的编码,对索引进行非平凡的计算,然后返回它。然后可以通过调用 getThingAtIndex 获取实际的“事物”。另一方面,getThingAtIndex 假定您正在查询结构并且已经有一个索引。这两种方法中的后者更快,但更重要的是,我想避免将 thing 传递给 getThingAtIndex 或传递 可能导致的麻烦indexgetThingIndex

我正在考虑为 thing 和事物索引创建类型,就像这样:

struct Thing { uint64_t thing; }
struct ThingIndex { uint64_t idx; }

然后将上述函数的签名更改为

getThingIndex(Thing t)
getThingAtIndex(ThingIndex idx)

现在,尽管 ThingThingIndex 编码相同 底层类型,它们在编译时仍然是不同的,我 通过将索引传递给来减少犯愚蠢错误的机会 getThingIndexgetThingAtIndex 的事物。

但是,我担心这种方法的开销。功能 被调用了很多次(10s-100s of millions),我很好奇 编译器将优化这些结构的创建,这些结构本质上是 除了编码编译时类型信息外什么都不做。如果编译器不会 执行这样的优化,有没有办法创建这些类型的“丰富类型” 零开销?

最佳答案

看一下反汇编。

unsigned long long * x = new unsigned long long;
0110784E  push        8  
01107850  call        operator new (01102E51h)  
01107855  add         esp,4  
01107858  mov         dword ptr [ebp-0D4h],eax  
0110785E  mov         eax,dword ptr [ebp-0D4h]  
01107864  mov         dword ptr [x],eax  
*x = 5;
01107867  mov         eax,dword ptr [x]  
0110786A  mov         dword ptr [eax],5  
01107870  mov         dword ptr [eax+4],0  

还有结构。

struct Thing { unsigned long long a; };
Thing * thing = new Thing;
0133784E  push        8  
01337850  call        operator new (01332E51h)  
01337855  add         esp,4  
01337858  mov         dword ptr [ebp-0D4h],eax  
0133785E  mov         eax,dword ptr [ebp-0D4h]  
01337864  mov         dword ptr [thing],eax  
thing->a = 5;
01337867  mov         eax,dword ptr [thing]  
0133786A  mov         dword ptr [eax],5  
01337870  mov         dword ptr [eax+4],0  

两条指令没有区别。编译器不关心 this->a 是结构的成员,它访问它就像您刚刚声明 unsigned long long a 一样。

关于c++ - C++ 中 "rich type"结构的开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15689553/

相关文章:

c++ - 重载下标运算符导致访问冲突

c++ - lambda "call operator"和 "parenthesized lambda"

c - 在有限制的情况下玩一会儿 - C 编程

c++ - 正在打印空指针未定义行为吗?

c++ - Internet Explorer 如何通知其他浏览器代理设置更改?

java - 哪种数据结构? LinkedList 还是 Java 中的任何其他?

c++ - 全局对象是否提供比多个本地实例更好的性能?

python - 有效地重新堆叠 numpy ndarray

c++ - 结构中的 union 初始化

c代码中的困惑