I was benchmarking some code for a project with timeit (using a free replit, so 1024MB of memory):
code = '{"type":"body","layers":['
for x, row in enumerate(pixels):
for y, pixel in enumerate(row):
if pixel != (0, 0, 0, 0):
code += f'''{{"offsetX":{-start + x * gap},"offsetY":{start - y * gap},"rot":45,"size":{size},"sides":4,"outerSides":0,"outerSize":0,"team":"{'#%02x%02x%02x' % (pixel[:3])}","hideBorder":1}},'''
code += '],"sides":1,"name":"Image"}}
The loop runs for every single pixel inside a given image (not efficient of course, but I haven't implemented anything to reduce loop times yet), so any optimization I can get in the loop is worth it.
I remembered that f-strings are faster than string concatenation as long as you're combining 3+ strings—and as shown, I have a lot more than 3 strings being combined—so I decided to replace the += inside the loop with an f-string and see the improvement.
code = '{"type":"body","layers":['
for x, row in enumerate(pixels):
for y, pixel in enumerate(row):
if pixel != (0, 0, 0, 0):
code = f'''{code}{{"offsetX":{-start + x * gap},"offsetY":{start - y * gap},"rot":45,"size":{size},"sides":4,"outerSides":0,"outerSize":0,"team":"{'#%02x%02x%02x' % (pixel[:3])}","hideBorder":1}},'''
code += '],"sides":1,"name":"Image"}}
The results of 500 timeit iterations:
+= took 5.399778672000139 seconds
fstr took 6.91279206800027 seconds
I've rerun this multiple times; the above times are the best f-strings have done so far. Why are f-strings slower in this case?
PS: This is my first time posting a question here. Any suggestions on how to improve my future questions would be greatly appreciated :D