From eb2dce6801b06d29f9cb873e1d000b495f282b5d Mon Sep 17 00:00:00 2001 From: Frank Verhoeven Date: Fri, 8 Aug 2025 10:45:22 +0200 Subject: [PATCH] perf: Moved `array_merge` out of the loop when paginating results Calling `array_merge` inside a loop will copy the entire array into memory on every iteration (`O(n)`), moving this out of the loop will make it `O(1)`, reducing memory usage. --- .gitignore | 4 +++- src/Picqer/Carriers/SendCloud/Query/FindAll.php | 8 ++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 9e270ad..33fecf8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +.DS_Store +.idea composer.phar composer.lock -vendor/ \ No newline at end of file +vendor/ diff --git a/src/Picqer/Carriers/SendCloud/Query/FindAll.php b/src/Picqer/Carriers/SendCloud/Query/FindAll.php index 639afed..88ff8f6 100644 --- a/src/Picqer/Carriers/SendCloud/Query/FindAll.php +++ b/src/Picqer/Carriers/SendCloud/Query/FindAll.php @@ -21,11 +21,11 @@ public function all($params = [], ?int $maxPages = 1): array while (true) { $result = $this->connection()->get($this->url, $params); - $allRecords = array_merge($allRecords, $this->collectionFromResult($result)); + $allRecords[] = $this->collectionFromResult($result); if (! empty($result['next'])) { // Get the querystring params from the next url, so we can retrieve the next page - $params = parse_url($result['next'], PHP_URL_QUERY); + $params = \parse_url($result['next'], PHP_URL_QUERY); } else { // If no next page is found, all records are complete break; @@ -34,12 +34,12 @@ public function all($params = [], ?int $maxPages = 1): array $pages++; // If max pages is set and reached, also stop the loop - if (! is_null($maxPages) && $pages >= $maxPages) { + if (null !== $maxPages && $pages >= $maxPages) { break; } } - return $allRecords; + return \array_merge(...$allRecords); } public function collectionFromResult($result): array