-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsample_file_cache.js
76 lines (59 loc) · 1.52 KB
/
sample_file_cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
let Lru = require("./lrucache.js").Lru;
let fs = require("fs");
let path = require("path");
let fileCache = new Lru(500, async function(key,callback){
// cache-miss data-load algorithm
fs.readFile(path.join(__dirname,key),function(err,data){
if(err) {
callback({stat:404, data:JSON.stringify(err)});
}
else
{
callback({stat:200, data:data});
}
});
},1000 /* cache element lifetime */);
// test with a file
// cache-miss
let t1 = Date.now();
fileCache.get("./test.js",function(dat){
console.log("Cache-miss time:");
console.log(Date.now()-t1);
console.log("file data:");
console.log(dat.data.length+" bytes");
// cache-hit
t1 = Date.now();
fileCache.get("./test.js",function(dat){
console.log("Cache-hit time:");
console.log(Date.now()-t1);
console.log("file data:");
console.log(dat.data.length+" bytes");
});
});
// cache-miss
setTimeout(function(){
// cache-miss
let t2 = Date.now();
fileCache.get("./test.js",function(dat){
console.log("Cache-miss time:");
console.log(Date.now()-t2);
console.log("file data:");
console.log(dat.data.length+" bytes");
});
},2500);
/*
output on my computer (ubuntu has its own file cache too, so it is less effective):
Cache-miss time:
13
file data:
2088 bytes
Cache-hit time:
0
file data:
2088 bytes
Cache-miss time:
1
file data:
2088 bytes
the second cache-miss is faster because of ubuntu's file cache but there is still the api latency of file-access
*/