Objective-Cがどのくらい遅いのかが気になったので、生成〜アクセサ〜解放でざっくり比較。
Objective-Cはこんな感じ。
#import
#import @interface Test : Object
{
int cnt;
}
@end
@implementation Test
- (void) init{
self->cnt = 0;
}
- (void) setCnt: (int)new_cnt{
self->cnt = new_cnt;
}
- (int) getCnt{
return self->cnt;
}
@end
int main(){
int i,j;
printf("Start?n");
for(i = 0; i < 5000; i++){
Test *t = [Test new];
for(j = 0; j < 5000; j++){
[t setCnt: [t getCnt] + 1];
}
[t free];
}
return 0;
}
#include class Test
{
int cnt;
public:
Test();
void setCnt(int);
int getCnt(void);
};
Test::Test(){
this->cnt = 0;
}
void Test::setCnt(int cnt){
this->cnt = cnt;
}
int Test::getCnt(void){
return this->cnt;
}
int main(){
int i,j;
printf("Start?n");
for(i = 0; i < 5000; i++){
Test *t = new Test();
for(j = 0; j < 5000; j++){
t->setCnt(t->getCnt() + 1);
}
delete t;
}
return 0;
}
両方とも適当な最適化オプションでコンパイルして、timeで比較。
-O0 | -O1 | -O3 | |
---|---|---|---|
Objective-C | 0m2.919s | 0m1.846s | 0m1.600s |
C++ | 0m1.252s | 0m0.304s | 0m0.063s*2 |
動的バインディング VS 静的バインディングとはいえ、かなりの差に残念無念。とは言え、最適化のない状態では2.5倍くらいだから、健闘した方かな。