Index mapping explained

Index mapping (or direct addressing, or a trivial hash function) in computer science describes using an array, in which each position corresponds to a key in the universe of possible values.[1] The technique is most effective when the universe of keys is reasonably small, such that allocating an array with one position for every possible key is affordable.Its effectiveness comes from the fact that an arbitrary position in an array can be examined in constant time.

Applicable arrays

There are many practical examples of data whose valid values are restricted within a small range. A trivial hash function is a suitable choice when such data needs to act as a lookup key. Some examples include:

Examples

Using a trivial hash function, in a non-iterative table lookup, can eliminate conditional testing and branching completely, reducing the instruction path length of a computer program.

Avoid branching

Roger Sayle gives an example[2] of eliminating a multiway branch caused by a switch statement:

inline bool HasOnly30Days(int m)

Which can be replaced with a table lookup:

inline bool HasOnly30Days(int m)

Notes and References

  1. Book: Cormen. Thomas H.. Introduction to algorithms. 2009. MIT Press. Cambridge, Mass.. 9780262033848. 253–255. 3rd. 26 November 2015.
  2. Sayle. Roger Anthony. A Superoptimizer Analysis of Multiway Branch Code Generation. Proceedings of the GCC Developers' Summit. June 17, 2008. 103–116. 26 November 2015.