Jump to content

Index mapping

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Jan Winnicki (talk | contribs) at 17:22, 26 November 2015 (Examples: second example seems repetitive, so removing it). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

In practice there are many examples of data exhibiting a small range of valid values all of which are suitable for processing[clarification needed] using a trivial hash function including:

Examples

The following two examples demonstrate how a simple non-iterative table lookup, using a trivial hash function, can eliminate conditional testing & branching completely thereby reducing instruction path length significantly. Although both examples are shown here as functions, the required code would be better inlined to avoid function call overhead in view of their obvious simplicity.

Avoid branching

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

bool Has30Days(int m) {
  switch (m) {
    case 4:  // April
    case 6:  // June
    case 9:  // September
    case 11: // November
      return true;
    default:
      return false;
  }
}

Which can be replaced with a table lookup:

bool Has30Days(int m) {
  static const bool T[] = { 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0 };
  return T[m];
}

See also

References

  1. ^ Cormen, Thomas H. (2009). Introduction to algorithms (3rd ed.). Cambridge, Mass.: MIT Press. pp. 253–255. ISBN 9780262033848. Retrieved 26 November 2015.
  2. ^ Sayle, Roger Anthony (June 17, 2008). "A Superoptimizer Analysis of Multiway Branch Code Generation" (PDF). Proceedings of the GCC Developers’ Summit: 103–116. Retrieved 26 November 2015.