【问题标题】:C: Performant temporary variables to avoid frequent typecastingC:性能临时变量以避免频繁的类型转换
【发布时间】:2014-12-17 21:00:51
【问题描述】:

((My_LengthilyNamedClass *)this)->someMember

...我已经厌倦了这些出现在我的代码库中,甚至在同一个函数中出现很多次。

在 C 中处理此类事情的适当方法是什么?我知道将其复制到名称正确且名称较短的堆栈/自动变量是避免强制转换的一种方法,但我认为这会导致额外的、可能不必要的堆栈分配。

可以在单个函数中使用define 来简化操作吗? defines 是要走的路吗?由于这是实时处理框架的代码,而且这些东西随处可见,因此我最好坚持使用性能最高的代码。

【问题讨论】:

  • 临时变量并不总是导致开销,请参阅Do temp variables slow down my program?
  • 使用内联函数。
  • 顺便说一句 this 的原始类型是什么?
  • @ShafikYaghmour 谢谢...好的。
  • @DanAllen 可以是Variant风格的对象,也可以是多态的手动实现

标签: c performance variables temporary


【解决方案1】:

编译器非常擅长优化。我认为你不会有任何问题:

My_LengthilyNamedClass *const ptr = this;

如果你真的很偏执,你可以使用宏:

#define THIS ((My_LengthilyNamedClass *)this)

THIS->someMember = 5;

#undef THIS

【讨论】:

    【解决方案2】:

    如果你有很多这样的演员表,你可以改变:

    ((My_LengthilyNamedClass *)this)->someMember
    

    My_LengthilyNamedClass *that = (My_LengthilyNamedClass *) this;
    

    /* ... */

    that->someMember
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2016-09-15
      • 1970-01-01
      • 2015-08-18
      • 2020-01-18
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多