Rafael Vergnaud
Rafael Vergnaud

Reputation: 111

Slightly pedantic question: which is more efficient?

Which is more efficient? Or are they both equally efficient? What is going on in the underlying architecture in the starred lines?

(1)

for(int i = m_size; i > index; --i)
{
     int k = normalize(i);             ***
     m_data[k] = m_data[k - 1];
}

or (2)

int k = 0; ***

for(int i = m_size; i > index; --i)
{
     k = normalize(i);             ***
     m_data[k] = m_data[k - 1];
}

Upvotes: 1

Views: 83

Answers (4)

Ajay
Ajay

Reputation: 18411

Don't get bothered with such micro-level optimization. Let the compiler/optimizer do it for you. As per C++ style, the 2nd approach is better as it declares the variable close to the usage (as discussed in "Code Complete" book). Other than C style, the first approach is good if you want to use the variable after the loop.

Do note that the function normalize, the type of m_data, the operator [] involved, etc. all play role in optimization. Size of data, parallelism, processor architecture also plays an important role in the program's run time performance.

Upvotes: 2

Michael Kenzel
Michael Kenzel

Reputation: 15933

It's hard to say what's "going on in the underlying architecture" without knowing what architecture you're talking about. But in general, any question of the "which is more efficient" kind can only ever really be answered in the obvious way: By measuring which version ends up being more efficient in your particular application…

Note that any remotely useful compiler should turn both your examples into exactly the same machine code…

Upvotes: 2

Diodacus
Diodacus

Reputation: 673

This is not a problem of efficiency. The first approach is better one because it uses RAII (Resource Allocation Is Initialization) approach. The second one is more C-style. You should declare variables when you use it, not in the beginning of the functional block. See this example:

void f1(bool use)
{
    ComplexObject c; // creating an object that has very costly, time-and-memory-consuming initialization

    if (! use)
        return;
    c.someFunction();
}

See what I mean ?

Upvotes: 1

Gardener
Gardener

Reputation: 2660

snippet #1 is more efficient for a naive compiler because the second snippet requires the loading of 0 in the variable k.

A good compiler will recognize that k is not used before the loading of k in the for loop and will optimize away the extra assignment.

You can use snippet 2 without loading the 0: int k;

Upvotes: 4

Related Questions