简体   繁体   English

编译器优化问题

[英]Compiler optimization problem

Most of the functions in <functional> use functors. <functional>大多数<functional>使用仿函数。 If I write a struct like this: 如果我写这样的结构:

struct Test
{
   bool operator()
   {
       //Something
   }
   //No member variables
};

Is there a perf hit? 有没有打击? Would an object of Test be created? 是否会创建Test对象? Or can the compiler optimize the object away? 或者编译器可以优化对象吗?

Yes, the compiler can optimize "object creation" (which is trivial in this case) out if it wants so. 是的,如果需要,编译器可以优化“对象创建”(在这种情况下这是微不足道的)。 However if you really care you should compile your program and inspect the assembly code. 但是如果你真的在乎你应该编译你的程序并检查汇编代码。

Even if the compiler was having a bad day and somehow couldn't figure out how to optimize this (it's very simple as optimizations go) - with no data members and no constructor the "performance hit" to "create an object" would be at most one instruction (plus maybe a couple more to copy the object, if the compiler also doesn't figure out how to inline the function call that uses the functor) to increment the stack pointer (since every object must have a unique address). 即使编译器有一个糟糕的一天,并且不知何故无法弄清楚如何优化它(这非常简单,因为优化去) - 没有数据成员和没有构造函数,“创建对象”的“性能命中”将是大多数一条指令(如果编译器也没有弄清楚如何内联使用仿函数的函数调用),那么复制对象可能会增加堆栈指针(因为每个对象必须有一个唯一的地址)。 "Creating objects" is cheap . “创建对象”很便宜 What takes time is allocating memory , via new (because the OS has to be petitioned for the memory, and it has to search for a contiguous block that isn't being used by something else). 需要花费时间的是通过new 分配内存 (因为操作系统必须为内存请求,并且它必须搜索没有被其他东西使用的连续块)。 Putting things on the stack is trivial. 将东西放在堆栈上是微不足道的。

GCC at least can optimize the object creation and inline your functor, so you can expect performance as with hand-crafted loop. GCC至少可以优化对象创建并内联您的仿函数,因此您可以期待与手工制作的循环一样的性能。 Of cource you must compile with -O2. 对于cource,您必须使用-O2进行编译。

There is no "use" of the structure, so as the code currently stands, it is still just a definition (and takes up no space). 结构没有“使用”,因此代码目前仍然只是一个定义(并且不占用空间)。

If you create an object of type Test , it will take up non-zero space. 如果您创建一个Test类型的对象,它将占用非零空间。 If the compiler can deduce that nothing takes its address (or anything similar), it is free to optimize away the space usage. 如果编译器可以推断出没有任何内容(或类似的东西),则可以自由地优化空间使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM