Initializing variable vs just using the list.split index; faster? better?

I’ve written a time_calculator, it works fine, the code is very compact; maybe too compact. The first line is

start_mins = 60 * int(start.split()[0].split(':')[0]) + int(start.split()[0].split(':')[1]) + 720 if 'PM' in start.split()[1] else 60 * int(start.split()[0].split(':')[0]) + int(start.split()[0].split(':')[1])

Its an inline if else statement, with only ‘start’ (ie ‘8:16 PM’) as input, and only ‘start_mins’ (the time in ‘start’, expressed in minutes, ie 1216 in this case) as output.

Difficult to read, and difficult to debug without documenting all steps that led up to this, but the idea was to a) keep the number of lines down, and b) create something that executes fast.

My question is, would this code execute faster if, instead of repeatedly refering to list.split indexes, I assigned their values to variables? Does the interpreter/compiler keep copies of indexes of split lists in RAM to refer to, or does it have to re-split it each time it encounters a new reference to it in code? I’m guessing that’s what would affect execution speed the most.

I’ll put the code up on replit when I feel like I’ve understood this issue.

Thanks! And happy new year to all.

As split will be run each time again, assigning result of split to variable, and then reusing it, will make code run faster.

I’ve run quick test using built-in timeit module, result is in seconds.

>>> timeit.timeit("60 * int(start.split()[0].split(':')[0]) + int(start.split()[0].split(':')[1]) + 720 if 'PM' in start.split()[1] else 60 * int(start.split()[0].split(':')[0]) + int(start.split()[0].split(':')[1])", "start='8:16 PM'")
1.075492335000007

>>> timeit.timeit("""time, am_pm = start.split()
hours, minutes = time.split(':')
60 * int(hours) + int(minutes) + 720 if 'PM' in am_pm else 60 * int(hours) + int(minutes)""", "start='8:16 PM'")
0.6952605769999991

Version with splits run just once is faster. However considering timeit by default runs command 1000000 times, the difference in the efficiency between the two in this case, for a code that will be run just once is marginal.

I’d recommend focusing on readability first. And optimize efficiency if there’s specific concern regarding it.

Thank you, I’ll have ago with timeit, I did wonder how that would be done.

I agree about readability, I realised the difference would inconsequential in this case, but I was too curious about it not to find out.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.