Skip to content

Commit

Permalink
Reduce memory allocations/improve perf of Counter
Browse files Browse the repository at this point in the history
  • Loading branch information
zbjornson committed Aug 4, 2021
1 parent 66f50b6 commit 65cef4c
Showing 1 changed file with 26 additions and 39 deletions.
65 changes: 26 additions & 39 deletions lib/counter.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,36 @@ class Counter extends Metric {
* @returns {void}
*/
inc(labels, value) {
if (!isObject(labels)) {
return inc.call(this, null)(labels, value);
let hash;
if (isObject(labels)) {
hash = hashObject(labels);
validateLabel(this.labelNames, labels);
} else {
value = labels;
labels = {};
}

const hash = hashObject(labels);
return inc.call(this, labels, hash)(value);
if (value && !Number.isFinite(value)) {
throw new TypeError(`Value is not a valid number: ${util.format(value)}`);
}
if (value < 0) {
throw new Error('It is not possible to decrease a counter');
}

if (value === null || value === undefined) value = 1;

setValue(this.hashMap, value, labels, hash);
}

/**
* Reset counter
* @returns {void}
*/
reset() {
return reset.call(this);
this.hashMap = {};
if (this.labelNames.length === 0) {
setValue(this.hashMap, 0);
}
}

async get() {
Expand All @@ -47,12 +63,10 @@ class Counter extends Metric {
};
}

labels() {
const labels = getLabels(this.labelNames, arguments) || {};
validateLabel(this.labelNames, labels);
const hash = hashObject(labels);
labels(...args) {
const labels = getLabels(this.labelNames, args) || {};
return {
inc: inc.call(this, labels, hash),
inc: this.inc.bind(this, labels),
};
}

Expand All @@ -63,38 +77,11 @@ class Counter extends Metric {
}
}

const reset = function () {
this.hashMap = {};

if (this.labelNames.length === 0) {
this.hashMap = setValue({}, 0);
}
};

const inc = function (labels, hash) {
return value => {
if (value && !Number.isFinite(value)) {
throw new TypeError(`Value is not a valid number: ${util.format(value)}`);
}
if (value < 0) {
throw new Error('It is not possible to decrease a counter');
}

labels = labels || {};
validateLabel(this.labelNames, labels);

const incValue = value === null || value === undefined ? 1 : value;

this.hashMap = setValue(this.hashMap, incValue, labels, hash);
};
};

function setValue(hashMap, value, labels, hash) {
hash = hash || '';
function setValue(hashMap, value, labels = {}, hash = '') {
if (hashMap[hash]) {
hashMap[hash].value += value;
} else {
hashMap[hash] = { value, labels: labels || {} };
hashMap[hash] = { value, labels };
}
return hashMap;
}
Expand Down

0 comments on commit 65cef4c

Please sign in to comment.