LightTab2 LightTab2 - 1 year ago 68
C++ Question

Is using while(true) and (else) if (...) break; "better" in some cases?

std::wstring insert;
if (insert.empty()){
else if (insert.substr(0, 3) == L"`/`"){
else if ( == '\t'){
else if ( == L'#') break;
else { /*...*/ }

In my program it takes around 50 ticks(if I can name it such) before break is executed. I'm worried about the performance: would it be better if I just have used

while( != L'#')


Answer Source

If anything, the performance could only possibly be worse, because you'd be checking for '#' on every iteration, instead of just once as it is now.

As ever, measure and profile. These questions cannot be answered in the abstract.

Most of your execution time is probably spent generating a fresh std::string from that substr call; that includes a dynamic allocation! You'd be much better off examining each character individually, perhaps wrapping that in some sort of "string view" class that has comparison features.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download