Condensing code in Python can be very helpful. It often omits multiple characters, perhaps even multiple lines in some cases, and is absolutely essential in code golfing. However, does this shortening of code have any effect on performance? Is there a measurable benefit?
Say this basic hypothetical code,
import math
number = '5'
variable = math.ceil(float(number))
print(variable)
which would appear to run fine, was refactored, or condensed into
from math import ceil
print(ceil(float('5.1')))
Both programs run fine, without error, but why is the former much less common in production? The first code snippet appears easier to read and looks more simple. Is there a performance benefit that comes with the single line of code versus the elaborated form in the second part?
Im not too sure on the inner workings of a computer and how it runs code, but i believe the first one would run the tiniest bit slower because of the introduction of a new variable. I doubt it would be noticeable. But again, I know nothing about that, please inform me if I’m wrong and ill delete this.
The first has 77 bytes whereas the second is only 48 bytes, so there would be a slight improvement in the time it would take to run this.