Skip to content

Commit

Permalink
perf: improve performance of gauge inc() dec() (#503)
Browse files Browse the repository at this point in the history
  • Loading branch information
twoeths authored Aug 23, 2022
1 parent a33d294 commit e818812
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ project adheres to [Semantic Versioning](http://semver.org/).

- changed: typedef for pushgateway to reflect js implementation.

- Improve performance of `gague.inc()` and `gauge.dec()` by calling `hashObject()` once.

Pushgateway's typedef were missing promise return type. That was
causing vscode to think that push/pushAdd and delete didn't promise
resulting in incorrect behavior.
Expand Down
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 e818812

Please sign in to comment.