Skip to content

Commit

Permalink
perf: improve performance of gauge inc() dec()
Browse files Browse the repository at this point in the history
  • Loading branch information
twoeths committed Jun 15, 2022
1 parent 721829c commit 49295d1
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
15 changes: 13 additions & 2 deletions lib/gauge.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const type = 'gauge';

const {
setValue,
setValueDelta,
getLabels,
hashObject,
isObject,
Expand Down Expand Up @@ -50,7 +51,7 @@ class Gauge extends Metric {
value = getValueArg(labels, value);
labels = getLabelArg(labels);
if (value === undefined) value = 1;
set(this, labels, this._getValue(labels) + value);
setDelta(this, labels, value);
}

/**
Expand All @@ -63,7 +64,7 @@ class Gauge extends Metric {
value = getValueArg(labels, value);
labels = getLabelArg(labels);
if (value === undefined) value = 1;
set(this, labels, this._getValue(labels) - value);
setDelta(this, labels, -value);
}

/**
Expand Down Expand Up @@ -147,6 +148,16 @@ function set(gauge, labels, value) {
setValue(gauge.hashMap, value, labels);
}

function setDelta(gauge, labels, delta) {
if (typeof delta !== 'number') {
throw new TypeError(`Delta is not a valid number: ${util.format(delta)}`);
}

validateLabel(gauge.labelNames, labels);
const hash = hashObject(labels);
setValueDelta(gauge.hashMap, delta, labels, hash);
}

function getLabelArg(labels) {
return isObject(labels) ? labels : {};
}
Expand Down
15 changes: 15 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,21 @@ exports.setValue = function setValue(hashMap, value, labels) {
return hashMap;
};

exports.setValueDelta = function setValueDelta(
hashMap,
deltaValue,
labels,
hash = '',
) {
const value = typeof deltaValue === 'number' ? deltaValue : 0;
if (hashMap[hash]) {
hashMap[hash].value += value;
} else {
hashMap[hash] = { value, labels };
}
return hashMap;
};

exports.getLabels = function (labelNames, args) {
if (typeof args[0] === 'object') {
return args[0];
Expand Down

0 comments on commit 49295d1

Please sign in to comment.