├── README.md ├── cache-friendly.js └── cache-unfriendly.js /README.md: -------------------------------------------------------------------------------- 1 | # nodejs-cpu-cache 2 | 3 | Examples showing the impact of cache misses in an interpreted language 4 | 5 | ```console 6 | $ time node cache-friendly.js 7 | node cache-friendly.js 0.59s user 0.16s system 101% cpu 0.738 total 8 | $ time node cache-unfriendly.js 9 | node cache-unfriendly.js 1.04s user 0.13s system 101% cpu 1.145 total 10 | ``` 11 | 12 | ```sh 13 | perf stat -B -e cache-references,cache-misses,cycles,instructions,branches,fault -- node --interpreted-frames-native-stack --perf-basic-prof cache-unfriendly.js 14 | ``` 15 | -------------------------------------------------------------------------------- /cache-friendly.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert') 2 | 3 | const width = 1e4; 4 | const height = 1e4; 5 | 6 | let valueToAvoidDeadCode; 7 | 8 | const image = []; 9 | 10 | for(let x = 0; x < width; ++x) { 11 | image[x] = [] 12 | for(let y = 0; y < height; ++y) { 13 | image[x][y] = 0 14 | } 15 | } 16 | 17 | for(let x = 0; x < width; ++x) { 18 | for(let y = 0; y < height; ++y) { 19 | valueToAvoidDeadCode = image[x][y]; 20 | } 21 | } 22 | 23 | assert.ok(valueToAvoidDeadCode === 0) 24 | -------------------------------------------------------------------------------- /cache-unfriendly.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert') 2 | 3 | const width = 1e4; 4 | const height = 1e4; 5 | 6 | let valueToAvoidDeadCode; 7 | 8 | const image = []; 9 | 10 | for(let x = 0; x < width; ++x) { 11 | image[x] = [] 12 | for(let y = 0; y < height; ++y) { 13 | image[x][y] = 0 14 | } 15 | } 16 | 17 | for(let y = 0; y < height; ++y) { 18 | for(let x = 0; x < width; ++x) { 19 | valueToAvoidDeadCode = image[x][y]; 20 | } 21 | } 22 | 23 | assert.ok(valueToAvoidDeadCode === 0) 24 | --------------------------------------------------------------------------------