Will the memory usage increase with the number of discord servers? #1282
-
$this->discord = new Discord([ |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
$this->discord->on('INTERACTION_CREATE', function (Interaction $interaction) {});2500 guild used 2 gigabytes? |
Beta Was this translation helpful? Give feedback.
-
The short answer to your question is yes. The long answer is that it depends. We have added support via the <?php
namespace Discord\Helpers;
trait LRUTrait
{
protected array $accessOrder = [];
protected int|bool $capacity = 1000; // Default capacity
protected array $expirations = [];
public function setCapacity(int|bool $capacity): void
{
$this->capacity = $capacity;
}
public function getCapacity(): int|bool
{
return $this->capacity;
}
public function get(string $key, mixed $default = null): mixed
{
if (isset($this->items[$key])) {
$this->updateAccessOrder($key);
return $this->items[$key];
}
return $default;
}
public function set(string $key, mixed $value): bool
{
if ($this->capacity !== false && $this->capacity !== -1 && count($this->items) >= $this->capacity) {
$this->evict();
}
$this->items[$key] = $value;
$this->updateAccessOrder($key);
return true;
}
protected function updateAccessOrder(string $key): void
{
$this->accessOrder = array_diff($this->accessOrder, [$key]);
$this->accessOrder[] = $key;
}
protected function evict(): void
{
$oldestKey = array_shift($this->accessOrder);
unset($this->items[$oldestKey], $this->expirations[$oldestKey]);
}
public function setExpiration(string $key, null|int|\DateInterval $ttl): void
{
if ($ttl === null) {
unset($this->expirations[$key]);
} elseif (is_int($ttl)) {
$this->expirations[$key] = time() + $ttl;
} elseif ($ttl instanceof \DateInterval) {
$expiration = (new \DateTime())->add($ttl);
$this->expirations[$key] = $expiration->getTimestamp();
}
}
protected function isExpired(string $key): bool
{
return isset($this->expirations[$key]) && $this->expirations[$key] < time();
}
protected function remove(string $key): void
{
unset($this->items[$key], $this->expirations[$key]);
$this->accessOrder = array_diff($this->accessOrder, [$key]);
}
} I'm pretty sure I'm going to take the above approach to implement LRU policies in a future update of the library. I need to do some testing and likely fiddle with some stuff, but it should work. |
Beta Was this translation helpful? Give feedback.
The short answer to your question is yes. The long answer is that it depends. We have added support via the
CacheInterface
to allow bot developers to set up their own Redis (or other interface-compliant tooling) to externalize the memory instead of using theAbstractRepository
. We are also investigating ways that LRU policies can be enforced directly at either theAbstractRepository
orCollection
level (which the AbstractRepository extends), including the addition of a trait that overrides some of the behaviors. An example of such a trait might look like this: