Skip to content

Commit

Permalink
store buffer contents in string instead of array (#976)
Browse files Browse the repository at this point in the history
array buffer is stupid inefficient due to the way PHP arrays operate (as
hashtables). instead, just store the bytes in a string which is more
like a `uint8_t*`.
  • Loading branch information
davidcole1340 authored Nov 12, 2022
1 parent 3b559e4 commit 356ea9d
Showing 1 changed file with 6 additions and 19 deletions.
25 changes: 6 additions & 19 deletions src/Discord/Helpers/Buffer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,12 @@
*/
class Buffer extends EventEmitter implements WritableStreamInterface
{
/**
* Pointer to the head of the buffer.
*
* @var int
*/
private $readPointer = 0;

/**
* Internal buffer.
*
* @var char[]
* @var string
*/
private $buffer = [];
private $buffer = '';

/**
* Array of deferred reads waiting to
Expand Down Expand Up @@ -73,9 +66,7 @@ public function write($data): bool
return false;
}

for ($i = 0; $i < strlen((string) $data); $i++) {
$this->buffer[] = $data[$i];
}
$this->buffer .= (string) $data;

foreach ($this->reads as $key => [$deferred, $length]) {
if (($output = $this->readRaw($length)) !== false) {
Expand All @@ -98,12 +89,9 @@ public function write($data): bool
*/
private function readRaw(int $length)
{
if ((count($this->buffer) - $this->readPointer) >= $length) {
$output = '';

for ($i = 0; $i < $length; $i++) {
$output .= $this->buffer[$this->readPointer++];
}
if (strlen($this->buffer) >= $length) {
$output = substr($this->buffer, 0, $length);
$this->buffer = substr($this->buffer, $length);

return $output;
}
Expand Down Expand Up @@ -217,7 +205,6 @@ public function close(): void

$this->buffer = [];
$this->closed = true;
$this->readPointer = 0;
$this->emit('close');
}
}

0 comments on commit 356ea9d

Please sign in to comment.