String comparison version single character comparison performance

In a c++ exercise website, I found out that the following code

int finalValueAfterOperations(vector<string>& operations) 
{
    int result = 0;
    for(int i = 0; i < operations.size(); ++i)
    {
        operations[i] == "++X" || operations[i] == "X++"?  ++result : --result;
    }

    return result;
}

is faster than

int finalValueAfterOperations(vector<string>& operations) 
{
    int result = 0;
    for(int i = 0; i < operations.size(); ++i)
    {
        operations[i][1] == '+'? ++result : --result;
    }

    return result;
}

What may be the underlying reasons for this?

I would assume that my single character checking would be more efficient than the full string comparison. I guess the comparison implementation has some optimization happening under the hood, but I am not sure what happens. Does someone have any idea?



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation