• Час читання ~5 хв
  • 10.10.2023

Як розробники, наш вибір може значно вплинути на продуктивність і використання пам'яті нашими програмами. Laravel пропонує нам різноманітні методи отримання даних з баз даних, такі як Методget(), що використовує функцію fetchAll(), отримує всі записи, chunk(), і lazy(). Ця стаття має на меті дослідити ці методи, висвітливши їх унікальні характеристики. Ми порівняємо їх, використовуючи деякі неофіційні тести, щоб зрозуміти їх вплив на використання пам'яті та швидкість. Зауважимо, що ці критерії не є науковими, але повинні надати корисну порівняльну картину.

Короткі підсумкові

Method Description Eager Load Low Memory Concurrent Safe
Методget(), що використовує функцію fetchAll(), отримує всі записи Fetches all records at once, fastest method. Yes No Yes
chunk() Retrieves data in small “chunks,” conserving memory. Yes Yes No
cursor() Retrieves data one record at a time, saving memory. No Yes Yes
lazy() Fetches records in small segments using PHP generators, simplifying the syntax. No Yes No

тести Зверніть

увагу, що тести, використані в цій статті, не є науковими і проводилися на системі, що працює під управлінням Laravel 8.74 і PHP 7.4.25 на macOS з Laravel Valet. Всі тести проводилися з Laravel 8.74 і PHP 7.4.25 на macOS з Laravel Valet.

10 000 записів 100 000 записів

Method Memory Time
Методget(), що використовує функцію fetchAll(), отримує всі записи 26 MB 261ms
cursor() 12 MB 460ms
lazy() 9MB 300ms
chunk() by 500 6MB 400ms

Методи

Method Memory Time
Методget(), що використовує функцію fetchAll(), отримує всі записи 277 MB 2.72sec
cursor() 75 MB 5.8sec
lazy() 9MB 5.4sec
chunk() by 500 6MB 7.56sec

Методget(), що використовує функцію fetchAll(), отримує всі записи

Методget(), що використовує функцію fetchAll(), отримує всі записи

The Методget(), що використовує функцію fetchAll(), отримує всі записи method, employing the fetchAll() function, fetches all database records in a single operation. This method offers the highest speed among the alternatives; however, it comes at the cost of significant memory consumption. Thus, it’s best-suited for scenarios where you’re working with smaller datasets and where ample memory resources are available.

  • Пропонує найшвидший пошук даних
  • Споживає великий обсяг пам'яті

chunk()

The chunk() method uses fetchAll() to retrieve data, similar to the Методget(), що використовує функцію fetchAll(), отримує всі записи method. However, instead of retrieving all records at once, it breaks the process down into smaller, manageable “chunks”. This approach dramatically reduces memory consumption, especially for larger datasets, by limiting the number of records retrieved at once based on a specified chunk size.

Despite being slower than Методget(), що використовує функцію fetchAll(), отримує всі записи, chunk() shines in scenarios where memory conservation is paramount. When performing operations that involve iterating and updating records simultaneously, consider using chunkById() to avoid potential issues, particularly when dealing with changes to primary or foreign keys.

  • Best for memory conservation, especially with larger datasets
  • Less speedy in comparison to Методget(), що використовує функцію fetchAll(), отримує всі записи
  • Potential complications in concurrency. If you are updating the same records you are iterating over (within the chunk operation), you may run into issues.

cursor()

The cursor() method leverages PHP´s fetch() function to retrieve records from the database buffer one at a time. As a result, it uses less memory than Методget(), що використовує функцію fetchAll(), отримує всі записи, making it more efficient for handling larger datasets. However, the trade-off is speed; it’s slower due to its one-by-one record iteration. An important advantage of cursor() is its consistency in processing datasets that might be subject to change during the processing period.

  • Effective memory usage - ideal for large datasets
  • Consistently processes datasets even when data changes during the operation
  • Slower than Методget(), що використовує функцію fetchAll(), отримує всі записи
  • Unable to handle eager loading of relationships
  • There’s a potential for memory exhaustion depending on the buffer size, particularly with extremely large collections

lazy()

Представлений у Laravel 8, lazy() метод є більш дружньою chunk()до синтаксису версією . Подібно , chunk()lazy() витягує записи невеликими сегментами. Однак замість того, щоб вимагати зворотного виклику, lazy() використовує PHP-генератори. Це призводить до спрощеного синтаксису, оскільки повертає LazyCollection для вашої зручності.

Метод lazy() забезпечує баланс між ефективним використанням пам'яті та читабельністю. Під час обробки великих наборів даних і виконання операцій, які передбачають одночасне ітерування та оновлення записів, можна використовувати lazyById() для підтримки узгодженості даних, особливо під час оновлення первинних або зовнішніх ключів.

  • Efficient memory usage similar to chunk()
  • Provides a cleaner syntax due to PHP generators
  • Slower than Методget(), що використовує функцію fetchAll(), отримує всі записи
  • Unable to handle eager loading of relationships
  • Possible concurrency Issues: If the underlying data changes during the iteration process, there might be inconsistencies in the results.
  • Suited for operations that require simultaneous iteration and updates on records, using lazyById()

Висновок

As we’ve explored, Laravel offers a variety of methods for data retrieval, each with its own unique strengths and weaknesses. The Методget(), що використовує функцію fetchAll(), отримує всі записи and chunk() methods, perhaps the most commonly used, offer distinct benefits. Методget(), що використовує функцію fetchAll(), отримує всі записи, while fast and capable of eager loading, consumes substantial memory, which may limit its utility with large datasets. On the other hand, chunk() method allows for memory efficiency with larger datasets and supports eager loading, but isn’t safe for operations where data changes concurrently.

Менш поширений, але все ще потужний, метод cursor() виділяється своєю ефективністю пам'яті та одночасною безпекою, незважаючи на те, що він повільніший і не підтримує нетерпляче завантаження. Нарешті, новачок в екосистемі Laravel забезпечує баланс chunk()ефективності пам'яті та простішого синтаксису, але, як cursor()і , lazy()не підтримує жадібне завантаження та небезпечний при одночасній зміні даних.

Зрештою, вибір методу повинен керуватися конкретними потребами вашої програми:

  • Розмір ваших даних
  • Доступна системна пам'ять
  • Вимога до жадібного завантаження
  • Чи можуть дані змінитися під час операції.

While Методget(), що використовує функцію fetchAll(), отримує всі записи and chunk() are popular for a reason, every method has its place, and the optimal choice always depends on the context. Equipped with an understanding of each method’s trade-offs, you’re now prepared to make an informed decision that best optimizes your application’s performance and memory usage.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

Про мене

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

Про автора CrazyBoy49z
WORK EXPERIENCE
Контакти
Ukraine, Lutsk
+380979856297