Skip to content

Commit e818812

Browse files
authored
perf: improve performance of gauge inc() dec() (#503)
1 parent a33d294 commit e818812

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ project adheres to [Semantic Versioning](http://semver.org/).
2121

2222
- changed: typedef for pushgateway to reflect js implementation.
2323

24+
- Improve performance of `gague.inc()` and `gauge.dec()` by calling `hashObject()` once.
25+
2426
Pushgateway's typedef were missing promise return type. That was
2527
causing vscode to think that push/pushAdd and delete didn't promise
2628
resulting in incorrect behavior.

lib/gauge.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ const type = 'gauge';
88

99
const {
1010
setValue,
11+
setValueDelta,
1112
getLabels,
1213
hashObject,
1314
isObject,
@@ -50,7 +51,7 @@ class Gauge extends Metric {
5051
value = getValueArg(labels, value);
5152
labels = getLabelArg(labels);
5253
if (value === undefined) value = 1;
53-
set(this, labels, this._getValue(labels) + value);
54+
setDelta(this, labels, value);
5455
}
5556

5657
/**
@@ -63,7 +64,7 @@ class Gauge extends Metric {
6364
value = getValueArg(labels, value);
6465
labels = getLabelArg(labels);
6566
if (value === undefined) value = 1;
66-
set(this, labels, this._getValue(labels) - value);
67+
setDelta(this, labels, -value);
6768
}
6869

6970
/**
@@ -147,6 +148,16 @@ function set(gauge, labels, value) {
147148
setValue(gauge.hashMap, value, labels);
148149
}
149150

151+
function setDelta(gauge, labels, delta) {
152+
if (typeof delta !== 'number') {
153+
throw new TypeError(`Delta is not a valid number: ${util.format(delta)}`);
154+
}
155+
156+
validateLabel(gauge.labelNames, labels);
157+
const hash = hashObject(labels);
158+
setValueDelta(gauge.hashMap, delta, labels, hash);
159+
}
160+
150161
function getLabelArg(labels) {
151162
return isObject(labels) ? labels : {};
152163
}

lib/util.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,21 @@ exports.setValue = function setValue(hashMap, value, labels) {
2828
return hashMap;
2929
};
3030

31+
exports.setValueDelta = function setValueDelta(
32+
hashMap,
33+
deltaValue,
34+
labels,
35+
hash = '',
36+
) {
37+
const value = typeof deltaValue === 'number' ? deltaValue : 0;
38+
if (hashMap[hash]) {
39+
hashMap[hash].value += value;
40+
} else {
41+
hashMap[hash] = { value, labels };
42+
}
43+
return hashMap;
44+
};
45+
3146
exports.getLabels = function (labelNames, args) {
3247
if (typeof args[0] === 'object') {
3348
return args[0];

0 commit comments

Comments
 (0)