Skip to content

Commit 1bb9182

Browse files
authored
Merge pull request #260 from MagicDuck/array_set_perf
using native javascript Map in array-set to improve memory usage
2 parents 95a3c3b + b9a80cc commit 1bb9182

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

lib/array-set.js

+27-10
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
var util = require('./util');
99
var has = Object.prototype.hasOwnProperty;
10+
var hasNativeMap = typeof Map !== "undefined";
1011

1112
/**
1213
* A data structure which is a combination of an array and a set. Adding a new
@@ -16,7 +17,7 @@ var has = Object.prototype.hasOwnProperty;
1617
*/
1718
function ArraySet() {
1819
this._array = [];
19-
this._set = Object.create(null);
20+
this._set = hasNativeMap ? new Map() : Object.create(null);
2021
}
2122

2223
/**
@@ -37,7 +38,7 @@ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
3738
* @returns Number
3839
*/
3940
ArraySet.prototype.size = function ArraySet_size() {
40-
return Object.getOwnPropertyNames(this._set).length;
41+
return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
4142
};
4243

4344
/**
@@ -46,14 +47,18 @@ ArraySet.prototype.size = function ArraySet_size() {
4647
* @param String aStr
4748
*/
4849
ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
49-
var sStr = util.toSetString(aStr);
50-
var isDuplicate = has.call(this._set, sStr);
50+
var sStr = hasNativeMap ? aStr : util.toSetString(aStr);
51+
var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
5152
var idx = this._array.length;
5253
if (!isDuplicate || aAllowDuplicates) {
5354
this._array.push(aStr);
5455
}
5556
if (!isDuplicate) {
56-
this._set[sStr] = idx;
57+
if (hasNativeMap) {
58+
this._set.set(aStr, idx);
59+
} else {
60+
this._set[sStr] = idx;
61+
}
5762
}
5863
};
5964

@@ -63,8 +68,12 @@ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
6368
* @param String aStr
6469
*/
6570
ArraySet.prototype.has = function ArraySet_has(aStr) {
66-
var sStr = util.toSetString(aStr);
67-
return has.call(this._set, sStr);
71+
if (hasNativeMap) {
72+
return this._set.has(aStr);
73+
} else {
74+
var sStr = util.toSetString(aStr);
75+
return has.call(this._set, sStr);
76+
}
6877
};
6978

7079
/**
@@ -73,10 +82,18 @@ ArraySet.prototype.has = function ArraySet_has(aStr) {
7382
* @param String aStr
7483
*/
7584
ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
76-
var sStr = util.toSetString(aStr);
77-
if (has.call(this._set, sStr)) {
78-
return this._set[sStr];
85+
if (hasNativeMap) {
86+
var idx = this._set.get(aStr);
87+
if (idx >= 0) {
88+
return idx;
89+
}
90+
} else {
91+
var sStr = util.toSetString(aStr);
92+
if (has.call(this._set, sStr)) {
93+
return this._set[sStr];
94+
}
7995
}
96+
8097
throw new Error('"' + aStr + '" is not in the set.');
8198
};
8299

0 commit comments

Comments
 (0)