python - Huge time difference when making a set inside a list comprehension compared to outside -
i have test case below, find elements present in 2 strings , return them in order of first string. why second case, set(string2)
done inside list comprehension on order of magnitude slower?
import timeit timeit.timeit( """ import random, string string1 = ''.join(random.choice(string.ascii_uppercase) _ in range(100000)) string2 = ''.join(random.choice(string.ascii_uppercase) _ in range(100000)) v=set(string2) [x x in string1 if x in v] """, number=10, ) # 2.005337953567505 timeit.timeit( """ import random, string string1 = ''.join(random.choice(string.ascii_uppercase) _ in range(100000)) string2 = ''.join(random.choice(string.ascii_uppercase) _ in range(100000)) [x x in string1 if x in set(string2)] """, number=10, ) # 22.1062970161438
python building set(string2)
set every iteration of 'loop' in list comprehension. doesn't 'know' it's same set every time.
e.g. every time python executes list comprehension if
clause, x in set(string2)
evaluated, means set created every time. since x each char of 100000 character string, means (same) set being built 100000 times in second case, once in first case (where define set v
).
Comments
Post a Comment