Fastest way to perform string lookups? Fastest way to perform string lookups? python-3.x python-3.x

Fastest way to perform string lookups?


The dictionary lookup is the fastest possible way to perform this search. In doing an analysis like this, you would normally compare the Time Complexity of each process.

For the dictionary lookup, the time complexity is "constant time", or O(1). While this can mean it is generally an integer value of steps that the algorithm can take, it is literally one in this instance.

The other methods will require iteration (or in the case of the if elses traversal - which is essentially a similar approach). These will range from needing to look at all values O(n), to needing to look at some values, O(log n).

As n is the size of the examining set, and as the set gets larger, the variance in the results will as well, with the dictionary consistently outperforming the other options shown.

There is no possible way to be faster than O(1). The only downside to the approach you have shown is that it may require more memory as the set grows, this is referred to as the Spacial Complexity of the algorithm. In this instance though, since we only need one value per item in the set, the spacial complexity will be O(n) which is negligible.

In a general sense of optimizations, it is important to consider how much complexity is present in a current solution, and how much sense it makes to improve on that complexity. If improvements are to be made, they should be aimed at getting to different tiers of performance, for example getting from O(n) to O(log n) or O(log n) to O(1).

Time Complexity Comparisons
Image courtesy: http://bigocheatsheet.com/

Micro-optimizations tend to be of the case where an optimization is made to and from the same complexity tier, and these are often not constructive in and of themselves.