My programming fundamentals teacher had said in one of her classes that using the “break” or “continue” keywords is less efficient then using a boolean to exit a loop.
I wrote and ran a program written in Python to see if this was the case:
import time;
TIMES = 100000000
COMPARE_FROM = "foo"
COMPARE_TO = "roo"
def breakTest() :
while(True) :
break;
if(COMPARE_FROM == COMPARE_TO) :
boo = "boo"
def booleanTest() :
running = True;
while(running) :
running = False;
if(running):
if(COMPARE_FROM == COMPARE_TO) :
boo = "boo"
def main() :
breakTimeBefore = 0;
breakTimeAfter = 0;
booleanTimeBefore = 0;
booleanTimeAfter = 0;
print("running break test ...");
breakTimeBefore = time.time();
for i in range(0, TIMES, 1):
breakTest();
breakTimeAfter = time.time();
print("break test complete");
print("Time: %f seconds \n" % (breakTimeAfter - breakTimeBefore));
print("running boolean test ...");
booleanTimeBefore = time.time();
for i in range(0, TIMES, 1):
booleanTest();
booleanTimeAfter = time.time();
print("boolean test complete");
print("Time: %f seconds \n" % (booleanTimeAfter - booleanTimeBefore))
print("---- FINDINGS ----");
print("breakTest time: %f" % (breakTimeAfter - breakTimeBefore));
print("booleanTest time: %f" % (booleanTimeAfter - booleanTimeBefore));
print("diffrence: %f" % ((breakTimeAfter - breakTimeBefore) - (booleanTimeAfter - booleanTimeBefore)));
input("Press enter to close...");
main();
After running it three times, and averaging the results, i found that the breakTest was 6.25 seconds faster.
So is the break keyword more efficient or is my code wrong?
Your tests are not exactly equivalent. I think your teacher may have had something more like the following in mind:
As you can see below, putting the condition into the while statement instead of having an if/break does improve performance (and shorten code):
Note that this is just an example of the different ways to exit the loop and what I think your teacher meant. Of course if you were actually writing this code, you should use
for i in range(11): ...