Bug 1389381: Part 2 - Add slop to the maximum size of a LimitedSet. r=aswan

Truncating a Set can be relatively expensive, so truncating only after several
excessive entries have been added can save some cycles.

MozReview-Commit-ID: DIAXQ3ow2fa

--HG--
extra : rebase_source : 0a748ff076ba43659f6315b3e51316845200d300
This commit is contained in:
Kris Maglione 2017-08-12 11:08:35 -07:00
Родитель 81748f7c7f
Коммит 9e2904259b
1 изменённых файлов: 11 добавлений и 2 удалений

Просмотреть файл

@ -261,11 +261,20 @@ class EventEmitter {
/**
* A set with a limited number of slots, which flushes older entries as
* newer ones are added.
*
* @param {integer} limit
* The maximum size to trim the set to after it grows too large.
* @param {integer} [slop = limit * .25]
* The number of extra entries to allow in the set after it
* reaches the size limit, before it is truncated to the limit.
* @param {iterable} [iterable]
* An iterable of initial entries to add to the set.
*/
class LimitedSet extends Set {
constructor(limit, iterable = undefined) {
constructor(limit, slop = Math.round(limit * .25), iterable = undefined) {
super(iterable);
this.limit = limit;
this.slop = slop;
}
truncate(limit) {
@ -278,7 +287,7 @@ class LimitedSet extends Set {
}
add(item) {
if (!this.has(item) && this.size >= this.limit) {
if (!this.has(item) && this.size >= this.limit + this.slop) {
this.truncate(this.limit - 1);
}
super.add(item);