on master help sign in
dodrio/js/strace.js
80 lines 1.8 kB history raw
1export function initStrace() {
2 instrumentAll(Element.prototype);
3 instrumentAll(Document.prototype);
4 instrumentAll(Node.prototype);
5 instrumentAll(EventTarget.prototype);
6}
8const counts = new Map;
9counts.total = 0;
11let timer = null;
13function log(ctorName, kind, key) {
14 counts.total += 1;
16 const entry = `${kind} ${ctorName}#${key}`
17 const count = counts.get(entry);
18 if (count === undefined) {
19 counts.set(entry, 1);
20 } else {
21 counts.set(entry, count + 1);
22 }
24 if (timer !== null) {
25 clearTimeout(timer);
26 }
27 timer = setTimeout(dumpAndReset, 100);
30function dumpAndReset() {
31 const data = [...counts]
32 .sort((a, b) => b[1] - a[1])
33 .map(a => ({ "DOM Method": a[0], "Count": a[1] }));
35 data.push({ "DOM Method": "<total>", "Count": counts.total });
37 console.table(data, ["DOM Method", "Count"]);
39 counts.clear();
40 counts.total = 0;
43function instrument(proto, key, desc) {
44 const ctorName = proto.constructor.name;
46 if (typeof desc.value == "function") {
47 const f = desc.value;
48 desc.value = function (...args) {
49 log(ctorName, "call", key);
50 return f.apply(this, args);
51 };
52 }
54 if (typeof desc.get == "function") {
55 const get = desc.get;
56 desc.get = function (...args) {
57 log(ctorName, "get", key);
58 return get.apply(this, args);
59 };
60 }
62 if (typeof desc.set == "function") {
63 const set = desc.set;
64 desc.set = function (...args) {
65 log(ctorName, "set", key);
66 return set.apply(this, args);
67 };
68 }
70 Object.defineProperty(proto, key, desc);
73function instrumentAll(proto) {
74 for (const key of Object.keys(proto)) {
75 const desc = Object.getOwnPropertyDescriptor(proto, key);
76 if (desc.configurable) {
77 instrument(proto, key, desc);
78 }
79 }