Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
The main reason for Tuple to be very efficient in reading because ts immutable.
why immutable objects are easy to read?
The reason is tuples can be stored in the memory cache, unlike lists. The program always read from the lists memory location as it is mutable(Can change any time)
In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember "premature optimization is the root of all evil").
Python makes this very easy: timeit is your friend.
and...
So in this case, instantiation is almost an order of magnitude faster for the tuple, but item access is actually somewhat faster for the list! So if you're creating a few tuples and accessing them many many times, it may actually be faster to use lists instead.
Of course if you want to change an item, the list will definitely be faster since you'd need to create an entire new tuple to change one item of it (since tuples are immutable).