I've been writing C++ code for a while now, but there's something I've been wondering for some time, without being to find a clear answer.
My point here is the following: let's say I have a function (could be a method, could be static
, but not necessarily), and that function uses some "heavy" object(s) (such as a string that can't be determined easily at compile time, but that is constant throughout the execution). An example I've actually come across is the following:
/* Returns an endpoint for an API
* Based on the main API URL (getApiUrl())
*/
virtual QString getEndPointUrl() const override
{
QString baseUrl = getApiUrl();
QString endpointUrl = QString("%1/%2").arg(baseUrl, "endpoint");
return endpointUrl;
}
It's of course just an example (I know that QString
s have their own fancy Qt memory management features, but let's admit we're dealing with basic objects).
Is it a good idea to do the following?
virtual QString getEndPointUrl() const override
{
/* We determine baseUrl only once */
static const QString baseUrl = getApiUrl();
/* We compute endpointUrl only once */
static const QString endpointUrl = QString("%1/%2").arg(baseUrl, "endpoint");
return endpointUrl;
}
As you may have guessed, the idea here is to not determine the URL at every execution of getEndPointUrl
.
The only drawback I've found is the higher memory usage (since the objects are built the first time the function is called and destroyed only when the program ends).
Another thing is that it's considered a "better" practice to have stateless functions, but I don't really think this kind of behaviour can be qualified as a "state".
EDIT: I just wanted to point out that the values I compute are meaningless outside of the function, otherwise they could be a field of the enclosing class or whatever, but they're never used anywhere else.
What are your thoughts?