Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65925425/does-declaring-local-method-variables-for-error-handling-come-at-memory-or-perfo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...