索引映射
外观
索引映射(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].