Mengenal Chunk dan Cursor pada Laravel – Penting untuk performance
Function chunk dan cursor digunakan untuk mengambil data dalam jumlah besar dengan memperhatikan penggunaan memory.
Performance Comparison
10,000 records:
+-------------+-----------+------------+
| | Time(sec) | Memory(MB) |
+-------------+-----------+------------+
| get() | 0.17 | 22 |
| chunk(100) | 0.38 | 10 |
| chunk(1000) | 0.17 | 12 |
| cursor() | 0.16 | 14 |
+-------------+-----------+------------+
100,000 records:
+--------------+------------+------------+
| | Time(sec) | Memory(MB) |
+--------------+------------+------------+
| get() | 0.8 | 132 |
| chunk(100) | 19.9 | 10 |
| chunk(1000) | 2.3 | 12 |
| chunk(10000) | 1.1 | 34 |
| cursor() | 0.5 | 45 |
+--------------+------------+------------+
Key Differences
- cursor(): Optimized for speed
- chunk(): Optimized for consistent memory usage
When to Use What
Use cursor()
when speed is the priority and chunk()
when you need to maintain consistent memory usage below a certain threshold.
Test Environment
- Homestead 0.5.0
- PHP 7.0.12
- MySQL 5.7.16
- Laravel 5.3.22
References: