szumial
szumial

Reputation: 73

Does declaring local method variables for error handling come at memory or performance cost in C++?

I want to ensure my application takes care of error handling. I am using a driver API to communicate with some hardware device - for this I have implemented both getter and setter methods to read and assign certain parameter values. The getter functions are marked as const, since they are not intended to change anything. The API can return an integer other than 0, in case an issue is encountered. The way I handle errors at the moment is as follows:

int MyClass::getParameterA() const
{
    int error;
    int parameterA;

    error = getParameterAPI(objectHandle, parameterName, &parameterA); // get parameter syntax mockup
    if(error != 0)
    {
        throw std::runtime_error("Cannot get parameterA.");
    }
    return parameterA;
}

I have implemented plenty of methods like in the example above. If the getters were not const, I could declare a global error variable in the header file and reuse it for each of the getters. Since this is not possible, does it affect performance or cause memory issues in case each such function has an internal error variable declared?

Upvotes: 0

Views: 49

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597885

does it affect performance or cause memory issues in case each such function has an internal error variable declared?

Typically not, especially for trivial types like int. Local variables are allocated on the calling thread's stack, and tend to be very fast to allocate and deallocate, since it is just a matter of adjusting the calling thread's current stack pointer by the size of the variable. Non-trivial types (strings, etc) may take a little more work, as their constructors and destructors have to be called on the allocated memory to ensure their data members are initialized/cleaned up properly.

Upvotes: 2

D-RAJ
D-RAJ

Reputation: 3382

Allocating memory (stack or heap) is not a good idea in a tight loop. This is because allocation is anyway a little costly (specially heap allocation).

In your method, you can ditch the error variable and insert the function right into the if condition so that you wont allocate extra variables:

if (getParameterAPI(objectHandle, parameterName, &parameterA) != 0)
{
    throw std::runtime_error("Cannot get parameterA.");
}

Other than that, your implementation doesn't take up much performance (depends on the driver, how you communicate between them and the logic behind getParameterAPI itself).

Note: If you take data into getParameterAPI() by reference (const or not), that might improve performance slightly, as you don't have copying in it (especially when it comes to memory). But still, it only affects if your arguments are quite large.

Upvotes: 1

Related Questions