访问本地和类成员变量之间的性能差异

时间:2011-11-25 13:30:15

标签: c++ performance

我在类成员函数中有以下代码:

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;
    }

但是,如果state是类成员变量而不是local变量,则性能会大幅下降(约5倍)。我正在阅读有关访问局部变量和类成员的差异,但文本通常会说它会略微影响性能。

如果有帮助:我使用MinGW GCC编译器和-O3选项。

1 个答案:

答案 0 :(得分:1)

我无法重现你的观察,在x86_64上用VS10和g ++进行测试。本地变体略快,可能是由于Alan Stokes在他的评论中所描述的,但最多只有10%左右。您应该检查您的时间,尝试排除任何其他问题,最好将您的所有代码减少到一个非常简单的测试 - 仍会显示此行为。

我认为我的测试用例非常类似于你的场景,至少就像你描述的那样:

#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;
}