提高应用程序性能的简单方法

时间:2012-01-04 05:12:27

标签: c++ performance

基本上我很想知道你走了多远,以确保你的用户得到最好的应用程序。

  1. 当两者都可能时,哪一个更喜欢动态/静态内存分配。
  2. 抓取int并使用shortint8_t。它会真的有用吗?或者它会更令人头痛?
  3. 动态分配“按比例”大量内存(由于缺少实际内存所需的信息)。然后将其重新分配给较小的内存(紧凑)并删除前者。例如。我分配了1000个单位的内存。然后在计算之后,我确定只需要400个单位。所以我分配新的400个单位,复制400个项目,然后删除1000个单位。在这个过程中,我最终会分配更多的内存,即1400个单位。那么我真的应该努力分配新的400个单位并让600个单位浪费吗? [主要问题]
  4. 是否有效使用union来帮助降低内存使用量?
  5. 我相信还有更重要的一点缺失。欢迎任何其他已知或本土的方式来增加记忆和时间表现。

3 个答案:

答案 0 :(得分:9)

  

7。我的担忧是否真实?

没有。您提到的所有内容通常都是无用的微优化,特别是对于现代编译器。编写大多数可读的代码,因为代码的读取次数比写入的次数多。

答案 1 :(得分:1)

这可能更适合Programmers.StackExchange.com。无论如何,我通常遵循unix的理念,即在你看到它之前不要固定瓶颈。

关于你的主要问题。这将使用更多的处理周期,而不仅仅是分配大块内存并完成它,因此在这种意义上效率较低。无论如何,记忆力现在相当消耗,效率,可重用性和可读性通常是我主要关注的问题。

如果您有疑问,请将-O3传递给您的编译器。

答案 2 :(得分:1)

2. Static. Don't allocate memory when you don't need to.

3. If the system is a 32-bit system, then the actual instructions to the processor will actually prefer uint32_t or int32_t...

5. If I need a generic data type that would need to be allocated several times in a loop, then a union can come in handy... to avoid allocating memory.

6. From my experience, allocating memory can be a slow process if it is done in a loop... You will see a performance increase if you allocate all the memory ahead of time, and then use it from a pool. When the system has go find huge blocks of memory, it can be a bottleneck.

7. In real-time situations with large chunks of memory... yes... otherwise... eh... not really

希望这会有所帮助......如果您遵循这种风格,您会发现性能有所提升。