I am currently trying to cleanup/improve on some code I finally got working.
Which of the two is faster between a while loop and the same command written over and over a set number of times.
EG.
count = 0
while count < 10:
print('hello')
count += 1
OR
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
print('hello')
The while loop is cleaner but is it faster? I am still quite new to this so my understanding is that in terms of the above procedural code, the while loop will run 32 statements in total compared to the print only statements which would run 10 times only:
- count is initially set to zero
- while evaluates count to be less than 10 (0)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (1)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (2)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (3)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (4)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (5)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (6)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (7)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (8)
- hello is printed
- count is incremented by one
- while evaluates count to be less than 10 (9)
- hello is printed
- count is incremented by one
- while evaluates count to no longer be less than 10 (10) While loop breaks out and processing ends
Based on the above, I would assume that the advantage of the while loop is neatness in code and speed of writing that code (not necessarily the speed in execution, albeit with computers been so powerful, one wouldn't notice.)
Am I correct in the above assumption?
EDIT: That was quick, I see some answers confirming my initial thoughts about optimization. Thanks.
The above code example is not related to my project, its just to show understanding.