nom*_*mad 3 c++ optimization struct overhead compile-time
我想在编译时跟踪当前采用相同类型参数的一些函数的"类型"信息.这是一个例子; 说我有两个功能getThingIndex(uint64_t t)和getThingAtIndex(uint64_t tidx).第一个函数将参数视为一个编码,对thing索引进行非平凡的计算,然后返回它.然后可以通过调用获得实际的"事物" getThingAtIndex.getThingAtIndex另一方面,假设您正在查询结构并且已经有索引.这两种方法的后者速度更快,而且更重要的是,我想避免可能造成的传递头痛thing到getThingAtIndex或通过传递index来getThingIndex.
我正在考虑创建类型thing和事物索引类似如下:
struct Thing { uint64_t thing; }
struct ThingIndex { uint64_t idx; }
Run Code Online (Sandbox Code Playgroud)
然后改变上面函数的签名
getThingIndex(Thing t)
getThingAtIndex(ThingIndex idx)
Run Code Online (Sandbox Code Playgroud)
现在,尽管事实上Thing并ThingIndex编码了相同的底层类型,但它们在编译时仍然是不同的,并且我通过将索引传递给getThingIndex某个东西来制造愚蠢错误的机会较少
getThingAtIndex.
但是,我担心这种方法的开销.这些函数被称为很多次(10s-100s,数百万次),我很好奇编译器是否会优化这些结构的创建,这些结构基本上只对编译时类型信息进行编码.如果编译器不会执行这样的优化,有没有办法创建这些类型的"富类型",零开销?
看一下拆卸.
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
Run Code Online (Sandbox Code Playgroud)
和结构.
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
Run Code Online (Sandbox Code Playgroud)
两条指令没有区别.编译器并不关心它this->a是结构的成员,而是像刚刚声明的那样访问它unsigned long long a.