こんにちは!
C++でclassのメソッド呼び出しは関数ポインタを使った呼び出しなのでオーバーヘッドがかかるって聞いたので検証していきます!
環境
$ gcc -v
Using built-in specs.
Target: x86_64-w64-mingw32
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 15.2.0 (Rev8, Built by MSYS2 project)
$ g++ -v
Using built-in specs.
Target: x86_64-w64-mingw32
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 15.2.0 (Rev8, Built by MSYS2 project)
計測方法
msys2のtimeで測ります.
オプションは-std=c11と-std=c++11を使います.
$ time .\time.exe
コード
test.c
#include <stdio.h>
int hello() {
printf("hello!");
return 0;
}
int main() {
hello();
return 42;
}
test2.c
#include <stdio.h>
int hello() {
printf("hello!");
return 0;
}
int main() {
int (*fp)() = hello;
fp();
return 42;
}
test3.cpp
#include <stdio.h>
namespace greeting {
int hello() {
printf("hello!");
return 0;
}
}
int main() {
greeting::hello();
return 42;
}
test4.cpp
#include <stdio.h>
class greeting {
private:
/* data */
public:
int hello() {
printf("hello!");
}
};
int main() {
greeting a;
a.hello();
return 42;
}
計測結果
-O0の時
$ gcc test.c -o test.exe -std=c11 -O0
$ gcc test2.c -o test2.exe -std=c11 -O0
$ g++ test3.cpp -o test3.exe -std=c++11 -O0
$ g++ test4.cpp -o test4.exe -std=c++11 -O0
$ time ./test.exe
hello!
real 0m0.110s
user 0m0.015s
sys 0m0.015s
$ time ./test2.exe
hello!
real 0m0.109s
user 0m0.015s
sys 0m0.015s
$ time ./test3.exe
hello!
real 0m0.157s
user 0m0.015s
sys 0m0.016s
$ time ./test4.exe
hello!
real 0m0.141s
user 0m0.015s
sys 0m0.015s
余り差がないですね.
-O3の時
$ gcc test.c -o test.exe -std=c11 -O3
$ gcc test2.c -o test2.exe -std=c11 -O3
$ g++ test3.cpp -o test3.exe -std=c++11 -O3
$ g++ test4.cpp -o test4.exe -std=c++11 -O3
$ time ./test.exe
hello!
real 0m0.141s
user 0m0.015s
sys 0m0.015s
$ time ./test2.exe
hello!
real 0m0.157s
user 0m0.000s
sys 0m0.015s
$ time ./test3.exe
hello!
real 0m0.158s
user 0m0.000s
sys 0m0.016s
$ time ./test4.exe
hello!
real 0m0.143s
user 0m0.015s
sys 0m0.015s
-O3にしたらみんな大体同じくらいのスピードですね.
終わり
どうやらそんなに変わらないみたいです.
次はもう少し再起呼び出しか何かを使って大量にアクセスしたときの結果を求めてみたいです.