I tried to test the speed among set
,list
and tuple
and got surprising results.
Before this, I have known that set
is faster than list
based on this answer.
Here is my test code:
import timeit,time
from sys import getsizeof as Size
List_Test = [range(1000)]
print("The Size of List is : {}".format(Size(List_Test)))
Set_Test = set(range(1000))
print("The Size of Set is : {}".format(Size(Set_Test)))
Tuple_Test = tuple(range(1000))
print("The Size of Tuple is : {}".format(Size(Tuple_Test)))
print("\nNow is to test speed\n")
time.sleep(3)
def Create_List():
List = [i for i in range(1000)]
def Test_List():
for i in List_Test:
if i == 6:
break
def Create_Set():
Set = set(i for i in range(1000))
def Test_Set():
for i in Set_Test:
if i == 6:
break
def Create_Tuple():
Tuple = tuple(i for i in range(1000))
def Test_Tuple():
for i in Tuple_Test:
if i == 6:
break
t = timeit.repeat(stmt="Create_List()",number=1000,setup="from __main__ import Create_List", repeat=30)
print("The Time of Create_List : {}".format(sum(t)/len(t)))
t = timeit.repeat(stmt="Create_Tuple()",number=1000,setup="from __main__ import Create_Tuple", repeat=30)
print("The Time of Create_Tuple : {}".format(sum(t)/len(t)))
t = timeit.repeat(stmt="Create_Set()",number=1000,setup="from __main__ import Create_Set", repeat=30)
print("The Time of Create_Set : {}".format(sum(t)/len(t)))
print("\n")
t = timeit.repeat(stmt="Test_List()",number=1000,setup="from __main__ import Test_List", repeat=30)
print("The Time of Test_List : {}".format(sum(t)/len(t)))
t = timeit.repeat(stmt="Test_Tuple()",number=1000,setup="from __main__ import Test_Tuple", repeat=30)
print("The Time of Test_Tuple : {}".format(sum(t)/len(t)))
t = timeit.repeat(stmt="Test_Set()",number=1000,setup="from __main__ import Test_Set", repeat=30)
print("The Time of Test_Set : {}".format(sum(t)/len(t)))
print("\nThe end")
Finally, I found that:
Size: Set > Tuple > List
Speed: List > Tuple > Set
I think my test code is wrong. What's wrong with it?
Edit:
I changed the test code:
List_Test = list(range(500000))
......
def Test_List():
randomNumber = random.randint(0,500000)
for i in List_Test:
if i == randomNumber:
break
# Other test code is the same
And the result of the test always is list ≈ tuple > set
.
When change the number 500000
(x20) to 10000000
,
It sometimes is list ≈ tuple ≈ set
,but often list ≈ tuple > set
.
May I infer that only when all of them have the same length(And the number of length is large),we can use set
(Although its size is much larger than tuple
and list
)?