简体   繁体   中英

is the operator overloading slow down performance?

im trying to make memory pool class and have to overload operator[], but theres a huge(2x) slow down:

  • T(overloaded) = 76.4043 ns
  • T(not-ovld) = 28.6016 ns

is it normal or im doing something wrong? thanks for help :)

compiler vc++2013 optimization disabled/full - same thing

class(main.cpp):

template<class T>
class pool{
public:
    T *cell;
    size_t size = 0;
public:
    pool(const size_t n ){
        size = n;
        cell = new T[size];
    }
    T& operator [](const size_t i) { return cell[i]; }
    T operator [](const size_t i)const { return cell[i]; }
};

main(main.cpp):

template<class T>
T F( T x){
    return x/2 % 100;
}

#define test_count 10000000

int main()
{
    pool<unsigned int> P(test_count);
    unsigned int sum = 0;
    resettimer();

    // test 1
    for (int i = 0; i < test_count; i++)
        P[i] = F(i);

    for (int i = 0; i < test_count; i++)
        sum = sum + P[i];

    cout << sum << endl;
    //
    printtimer();
    sum = 0;
    resettimer();

    // test2
    for (int i = 0; i < test_count; i++)
        P.cell[i] = F(i);

    for (int i = 0; i < test_count; i++)
        sum = sum + P.cell[i];

    cout << sum << endl;
    //
    printtimer();

    int q;
    cin >> q;
    return 0;
}

Problem was with Debug build, in Release build (optimization n stuff) all works like it should. Hehe stupid mistake but taught me something :) Conclusion - dont measure performence in debug mode ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM