我正在研究编写缓存,我发现有几处提到缓存大小是质数。
例如
Maximum number of objects must be a prime number for the cache count values. Range value is from 3 to a maximum number that is logical for the task and that does not affect performance. Non-prime numbers are automatically rounded up to the next higher prime number. If the number fails, the default value will be used.
最佳答案
假设我们有一个包含 m 个条目的缓存和一个使用模式,它会导致跨步行为,即它会命中某个 n 的每个第 n 个条目。该模式将环绕末端并在仍有空槽时再次击中一些条目。例如,如果缓存的大小为 10,并且使用模式每 6 个条目命中一次,它将按以下顺序命中(如果它以 0 开头):0, 6, 2, 8, 4, 0, 6, 2, 8 , 4, ... 所以一半的缓存将未被使用。在一般情况下,可以准确地说像这样的跨步行为将导致 1/GCD(n,m) 的行被使用而其他行留空。因此,如果 GCM(n,m) 为 1,我们只会在存在跨步行为的情况下得到充分利用。使缓存具有质数大小使得这很有可能。只有当 n=m 或 n 是 m 的倍数时,它才会失败,这对于不小的素数来说是不太可能的。
关于caching - 为什么缓存大小通常定义为素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43140040/