索引映射
外观
索引映射(Index mapping)也称为直接定址(direct addressing)或平凡散列函数(trivial hash function)是计算机科学中对阵列的应用,利用阵列查表来找到主键所有全集分别对应的值[1]。 此方式适用在主键全集不大的情形,因此可以针对每一个可能的主键分配记忆体。 其效能是源至在任何阵列中查表的时间复杂度都是常数。
适用的阵列
[编辑]有许多实例中的资料有效值限制在小范围内。此时适合使用平凡散列函数,以数值作为查表的键值,以下是一些例子:
例子
[编辑]利用平凡散列函数,非迭代式的查表法,可以完全消除条件判断以及分支,减少程式中的指令路径长度。
避免分支
[编辑]Roger Sayle提供一个程式[2],完全消除以下switch指令会有的多路分支:
inline bool HasOnly30Days(int m)
{
switch (m) {
case 4: // April
case 6: // June
case 9: // September
case 11: // November
return true;
default:
return false;
}
}
其作法是用以下的查表法:
inline bool HasOnly30Days(int m)
{
static const bool T[] = { 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0 };
return T[m-1];
}
参考资料
[编辑]- ^ Cormen, Thomas H. Introduction to algorithms 3rd. Cambridge, Mass.: MIT Press. 2009: 253–255 [26 November 2015]. ISBN 9780262033848.
- ^ Sayle, Roger Anthony. A Superoptimizer Analysis of Multiway Branch Code Generation (PDF). Proceedings of the GCC Developers' Summit. June 17, 2008: 103–116 [26 November 2015].