From Wikipedia, A cache miss is a failed attempt to read or write a piece of data in the cache, which results in a main memory access with much longer latency.
However, I don’t understand what kind of data we are talking about and how to reproduce this synthetically. Based on this answer, cache optimization is performed by adjusting the algorithm to avoid data fragmentation when accessing.
/* Array.prototype.flat polyfill */
Array.prototype.flat = function() {
this.reduce((a, v) => Array.isArray(v) ? a.concat(v.flat()) : a.concat(v), []);
};
/* Cache test */
const len = 100;
const generateArr = (len) => {
const mat = [...new Array(len)].map(() =>
[...new Array(len)].map(() => Math.round(Math.random() * 10))
);
return new Uint8Array(mat.flat(Infinity))
};
const arr = generateArr(len)
/* {1, 2, 3, 4, 5, 6, 7, 8, 9, n} */
const testFriendly = () => {
let total=0;
for (let x=0;x!=len;x+=10) {
for (let y=0;y!=10;y++) {
total+=arr[x+y];
}
}
};
/* {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 1, 11, 12, n}*/
const testUnfriendly = () => {
let total=0;
for (let y=0;y!=10;y++) {
for (let x=0;x!=len;x+=10) {
total+=arr[x+y];
}
}
};
const test = () => {
console.time("Cache-friendly");
for (let i=0; i!=7000; i++) {
testFriendly();
}
console.timeEnd("Cache-friendly");
console.time("Cache-unfriendly");
for (let i=0; i!=7000; i++) {
testUnfriendly();
}
console.timeEnd("Cache-unfriendly");
};
test()
test()
test()
test()
After the JIT completes, the friendly test runs faster, but not always. Is this a cache miss?
But can an application programmer get a cache miss on the NodeJS platform? Are there any anti-patterns in order to guarantee a cache miss and prevent similar in production code?