c - which is more efficient? repetitive assignment or repetitive checking -


if had loop checks specific value in array and, reason, must iterate on elements , cannot break midway.

which of following more efficient: blindly setting flag on each match, or checking if flag false before setting it.

bool happened = false; while (...) {   if (...) {     happened = true;   } } 

vs

bool happened = false; while (...) {   if (...) {     if (!happened) happened = true;   } } 

as far can tell, both more or less equivalent on assumption memory reads fast memory writes (ignoring instruction in second example). correct in conclusions?

the compiler make decision you, if use meaningful optimization. write whatever cleanest , makes sense. me first one, since less code , doesn't introduce more code paths. fun, did tests in clang 3.4 -o3:

bool happened = false; extern volatile int dontoptme1, dontoptme2, dontoptme3; while (dontoptme1) {   if (dontoptme2) {     happened = true;   } } dontoptme3 = happened; 

vs

bool happened = false; extern volatile int dontoptme1, dontoptme2, dontoptme3; while (dontoptme1) {   if (dontoptme2) {     if(!happened) happened = true;   } } dontoptme3 = happened; 

resulted in following in pseudo asm:

  mov      happened, 0   bra      loop_end loop_start:   selecteq dontoptme2, 0, happened, happened, 1 loop_end:   bczc     dontoptme1, loop_start exit:   store    dontoptme3, happened 

vs

  mov      happened, 0   bczs     dontoptme1, exit loop:   selectne dontoptme2, 0, r2, 1, 0   selecteq happened, 0, r3, 1, 0   ,      r3, r2, r3   selectne r3, 0, happened, 1, 0   bczc     dontoptme1, loop exit:   store    dontoptme3, happened 

the first more desirable. example of how restrictive volatile types are. surprised compiler couldn't transform second first.

note: selectxx means, if arg1 minus arg2 sets condition code xx, set arg3 arg4, otherwise set arg3 arg5. so: selectne dontoptme2, 0, r2, 1, 0 equivalent of: r2 = (dontoptme2 == 0) ? 1 : 0; in c


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -