类成员函数与等价正则函数的性能差异

问题描述 投票:0回答:1

我在 c++ 的两种编码方法之间进行选择:

struct something {
    int a[100];
    
    // constructors and other things

    void do_stuff(){
        // does something with array a
    }
};

int a[100]; 

void do_stuff(int a[100]){
    // also does something with array a
}

两者之间有什么性能差异吗?在优化方面,编译器对

struct
中的示例有何不同?对于多个变量和方法呢?

我知道使用结构/类可能更干净,我问这个问题是因为对于我正在做的事情,我可以在代码质量上做出妥协以获得额外的性能(如果有的话)。

c++ performance
1个回答
0
投票

使用 godbolt 检查装配可能会给你一个准确的答复: 现代 C/C++ 编译器生成优化代码,最近它们能够使用 SIMD 指令 (C++23),所以我认为这没有什么不同。您可以使用具有数组大小的指针将数组传递给第二个示例中的函数,而不是整个数组。

从你的第二个例子:

int a[100]; 

void do_stuff(int *a, size_t count){
    // also does something with array a
}

对于性能,它取决于“do_stuff”函数的作用以及您的程序必须处理 do_stuff 函数/方法的次数...... 您可以使用一些容器,例如来自 STL 或 Boost.org 库的 vector / map 和 algorithm / Iterator / manipulator。

您还可以查看此站点以了解开发人员如何优化代码以提高性能:

https://benchmarksgame-team.pages.debian.net/benchmarksgame/index.html

https://programming-language-benchmarks.vercel.app/

© www.soinside.com 2019 - 2024. All rights reserved.