كتب برنامج صغير أختبر فيه سرعة استخدام operator overloading [] و ال [] العادي في لغة ++C
فإتضح لي إن overloading أسرع من ال [] العادي وهذا هو البرنامج
#
include<iostream>
#include<ctime>
class array{
public:
array(int len)
{
a = new int[len];
}
int & operator[](int i)
{
if(i<0 || i >= 1000000)return a[0];
return a;
}
~array()
{
delete [] a;
}
private:
int * a;
};
int main()
{
array a1(1000000);
int *a2 = new int[1000000];
int i = 0;
clock_t c1 = clock();
for(;i<1000000;i++)
a1 = i;
c1 = clock() - c1;
i = 0;
clock_t c2 = clock();
for(;i<1000000;i++)
a2 = i;
c2 = clock() - c2;
std::cout<<"[] overloading = "<<c1<<"\n";
std::cout<<"[] predefined = "<<c2<<"\n";
delete [] a2;
}وطلعت لي إن c1 يستغرق 0 أما c2 يستغرق 15 فرحت لكود الأسبملي الناتج
فكان كالأتي :
ال [] operator overloading :
for_loop1: ; 29 : for(;i<1000000;i++) ; 30 : a1 = i; cmp esi, 999999 ; 000f423fH mov eax, ecx jbe SHORT overload_bracket mov eax, ebx overload_bracket: mov DWORD PTR [eax], esi add esi, 1 add ecx, 4 cmp esi, 1000000 ; 000f4240H jl SHORT foor_loop1
أما ال [] العادي :
for_loop2: ; 35 : for(;i<1000000;i++) ; 36 : a2 = i; mov eax, DWORD PTR _a2$[esp+40] mov DWORD PTR [eax+esi*4], esi add esi, 1 cmp esi, 1000000 ; 000f4240H jl SHORT for_loop2
فما أدري من وين جاءت سرعة ال overloading رغم إنه أكثر أسطر - بالنسبة للأسمبلي - وما وضعته هنا إلا لأنه سؤال في لغة الأسبملي أكثر منه في ++C فممكن أسمع تعليقاتكم أو إستنتاجاتكم ؟!!!!!!!!!!
ملاحظة إستخدم خيار release بدل من debug عند التجربة
