mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-17 12:03:31 +01:00
Cache array and keyArray in Collection (#771)
* Cache array and keyArray in Collection Cache array and keyArray in the Collection class to improve consecutive calls of collection.random() by around 400,000%, I think lel. The speed decrease (I assume) compared to the previous version when calling after it has changed is most likely negligible. * Fix for ESLint I think this fixes it.
This commit is contained in:
committed by
Schuyler Cebulskie
parent
2acfb16cb8
commit
53f5c2cb52
@@ -3,6 +3,16 @@
|
|||||||
* @extends {Map}
|
* @extends {Map}
|
||||||
*/
|
*/
|
||||||
class Collection extends Map {
|
class Collection extends Map {
|
||||||
|
set(key, value) {
|
||||||
|
super.set(key, value);
|
||||||
|
this.changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(key) {
|
||||||
|
super.delete(key);
|
||||||
|
this.changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns an ordered array of the values of this collection.
|
* Returns an ordered array of the values of this collection.
|
||||||
* @returns {Array}
|
* @returns {Array}
|
||||||
@@ -67,8 +77,11 @@ class Collection extends Map {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
random() {
|
random() {
|
||||||
const arr = this.array();
|
if (!this.cachedArray || this.cachedArray.length !== this.size || this.changed) {
|
||||||
return arr[Math.floor(Math.random() * arr.length)];
|
this.cachedArray = this.array();
|
||||||
|
this.changed = false;
|
||||||
|
}
|
||||||
|
return this.cachedArray[Math.floor(Math.random() * this.cachedArray.length)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -77,8 +90,11 @@ class Collection extends Map {
|
|||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
randomKey() {
|
randomKey() {
|
||||||
const arr = this.keyArray();
|
if (!this.cachedKeyArray || this.cachedKeyArray.length !== this.size || this.changed) {
|
||||||
return arr[Math.floor(Math.random() * arr.length)];
|
this.cachedKeyArray = this.keyArray();
|
||||||
|
this.changed = false;
|
||||||
|
}
|
||||||
|
return this.cachedKeyArray[Math.floor(Math.random() * this.cachedKeyArray.length)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in New Issue
Block a user