[Solved] why C style code is faster than C++ style code [closed]


Don’t force a flush:

cout << ret[i] << endl;

That is really inefficient forcing the stream to flush every time. Rather simply use the \n;

cout << ret[i] << `\n';

Also because C++ tried to maintain backward compatibility with C the C++ iostream are linked to the C iostreams. It is expensive to keep them in sync. If you are not using the C iostreams in your C++ application best to un-sync them:

int main() {
    std::ios::sync_with_stdio(false);

    // Your code
}

Building a string like this is not the most efficient way of doing it:

ret += 'x' + leftBot + rightBot + leftTop + rightTop;

Do what you did in C:

ret += 'x';
ret += leftBot;
ret += rightBot;
ret += leftTop;
ret += rightTop;

You may also want to make sure the string does not resize. In the C version you have a max size. Why not give the C++ the benefit of knowing this to prevent re-allocation.

std::string ret;
ret.reserve(MAX_LENGTH);

5

solved why C style code is faster than C++ style code [closed]