Anton Frolov
Anton Frolov

Reputation: 291

Performance difference between accessing local and class member variables

I have the following code in a class member function:

int state = 0;
int code = static_cast<int>(letter_[i]);
if (isalnum(code)) {
      state = testTable[state][0];
    } else if (isspace(code)) {
        state = testTable[state][2];
    } else if (code == OPEN_TAG) {
        state = testTable[state][3];
    } else if (code == CLOSE_TAG) {
        state = testTable[state][4];
    } else {
        state = testTable[state][1];
    }

    switch (state) {
    case 1: // alphanumeric symbol was read
        buffer[j] = letter_[i];
        ++j;
        break;
    case 2: // delimeter was read
        j = 0;
    //  buffer.clear();
        break;
    }

However, if state is a class member variable rather than local, the performance drops considerably (~ 5 times). I was reading about differences in accessing local variables and class members, but texts usually say that it affects performance very slightly.

If it helps: I am using MinGW GCC compiler with -O3 option.

Upvotes: 2

Views: 490

Answers (1)

zerm
zerm

Reputation: 2842

I could not reproduce your observation, testing on x86_64 with both, VS10 and g++. The local variant is slightly faster, probably due to what Alan Stokes described in his comment, but at most ~10%. You should check your timing, try to rule out any other problems and best would be the reduce all your code to a very simple test-cast which still shows this behavior.

I think my test-case resembles your scenario quite good, at least like you described it:

#include <iostream>
#include <boost/timer.hpp>

const int max_iter = 1<<31;
const int start_value = 65535;

struct UseMember
{
    int member;
    void foo()
    {
        for(int i=0; i<max_iter; ++i)
        {
            if(member%2)
                member = 3*member+1;
            else
                member = member>>1;
        }
        std::cout << "Value=" << member << std::endl;
    }
};

struct UseLocal
{
    void foo()
    {
        int local = start_value;
        for(int i=0; i<max_iter; ++i)
        {
            if((local%2)!=0) /* odd */
                local = 3*local+1;
            else /* even */
                local = local>>1;
        }
        std::cout << "Value=" << local << std::endl;
    }
};


int main(int argc, char* argv[])
{
    /* First, test using member */
    std::cout << "** Member Access" << std::endl;
    {
        UseMember bar;
        bar.member = start_value;
        boost::timer T;
        bar.foo();
        double e = T.elapsed();
        std::cout << "Time taken: " << e << "s" << std::endl;
    }

    /* Then, test using local */
    std::cout << "** Local Access" << std::endl;
    {
        UseLocal bar;
        boost::timer T;
        bar.foo();
        double e = T.elapsed();
        std::cout << "Time taken: " << e << "s" << std::endl;
    }
    return 0;
}

Upvotes: 1

Related Questions