refactor: optimizing dropoutEnrollment command #3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Benchmark Comparison
Before:

After:

Optimization Process
Identifying Bottlenecks
Initially, the dropout process fetched all enrollments into memory
(->get())
, then iterating one by one to check conditions and update records.This approach has resulted in:
Optimization Strategies
To improve performance, I implemented the following optimizations:
Joining Tables and Filter Data in SQL
Moved filtering logic using the database query using LEFT JOIN with NULL checks to avoids unnecessary PHP-level processing.
Batch Processing with chunkById
Instead of loading all data into memory, I used chunkById(), reduced memory consumption and improving efficiency.
Bulk Updates & Inserts
Used whereIn('id', $ids)->update() to update enrollments in bulk rather than by foreach every data.
Inserted activity logs using Activity::insert($activities), reducing query execution time.
Moving now() calls to variable $now to avoid repeated call and improving updated_at date consistency in every batch
Garbage Collection (gc_collect_cycles())
Forced garbage collection after each batch to free up memory.