laravel-model-status icon indicating copy to clipboard operation
laravel-model-status copied to clipboard

CHG: Optimize `scopeCurrentStatus` and `scopeOtherCurrentStatus` Quer…

Open alfreddagenais opened this issue 1 year ago • 0 comments

Overview

This PR proposes an optimization for the scopeCurrentStatus method in the laravel-model-status package. The current implementation uses a nested query with MAX(id) which can lead to performance issues on large datasets.

Changes

  • Modified the scopeCurrentStatus method to remove the nested MAX(id) query.
  • The query now directly fetches the latest status based on the id, assuming the latest status has the highest id.

Impact

  • This change significantly reduces the complexity of the query and improves the performance, especially in scenarios with a large number of status records.
  • The modification maintains the existing functionality and does not introduce breaking changes.

Tests

  • The existing tests were run to ensure that the functionality remains intact.
  • Additional tests may be required to specifically assess the performance improvements.

I believe this optimization will be beneficial for users experiencing performance issues with the current implementation of scopeCurrentStatus. Looking forward to your feedback and suggestions.


Proposed Test for Performance Evaluation

While making the optimizations to the scopeCurrentStatus method, I also devised a performance test to evaluate the improvements. It's important to note that the performance gains may vary depending on the specific server environment and database size. In my local testing environment, the performance difference was not significant, but it showed more noticeable improvements on a production-like server setup.

Here's the example test:

it('executes the currentStatus query efficiently', function () {
    // Prepare your test environment with a large amount of data

    $model = TestModel::create(['name' => 'model1']);
    for ($i=0; $i < 1000; $i++) {
        // Set up some test statuses
        $model->setStatus("status{$i}");
    }

    $startTime = microtime(true);
    $model->currentStatus('status999')->get(); // Make sure this status exists
    $endTime = microtime(true);

    $executionTime = $endTime - $startTime;
    // echo "Execution Time: " . $executionTime . " seconds\n";

    expect($executionTime)->toBeLessThan(1.0); // Choose an appropriate time limit
});

Important Note

This test is provided as an example to demonstrate how one might measure the performance improvements. The actual performance gains can be more significant on systems with larger datasets and in different server configurations. I recommend running this test in your specific environment to gauge the performance improvements.


Capture-2023-12-25_18-25-52-002150

Capture-2023-12-25_18-24-50-002149

alfreddagenais avatar Dec 25 '23 23:12 alfreddagenais