Dijkstra algorithm optimization/caching

后端 未结 3 908

I have the following Dijkstra algorithm with 3 input variables (start, stop and time). It takes about 0.5-1s to complete. My hosting provider says it\'s using too muc

3条回答
  •  醉话见心
    2020-12-20 04:18

    Micro-optimisations, but don't do:

    for ($p = 0; $p < sizeof($nextStopArray); $p++) { 
       ...
    }
    

    calculate the sizeof($nextStopArray) before the loop, otherwise you're doing the count every iteration (and this value isn't being changed)

    $nextStopArraySize = sizeof($nextStopArray);
    for ($p = 0; $p < $nextStopArraySize; ++$p) { 
       ...
    }
    

    There's a couple of places where this should be changed.

    And if you're iterating several thousand times, ++$p is faster than $p++

    But profile the function... find out which parts are taking the longest to execute, and look to optimise those.

    EDIT

    Get rid of array_push_key as a function, simply execute it inline... it's costing you an unnecessary function call otherwise

    Build an array of all nodes from your database outside of the while(true) loop... retrieve all the data in a single SQL query and build a lookup array.

    Replacing

    for ($p = 0; $p < sizeof($nextStopArray); $p++) { 
    

    with

    $nextStopArraySize = sizeof($nextStopArray);
    $p = -1
    while (++$p < $nextStopArraySize) { 
       ...
    }
    

    may also prove faster still (just check that the logic does loop through the correct number of times).

提交回复
热议问题