skip to Main Content

I want to get sessionIds array. I know 2 way to fill up and which one should i chooce?
Can usage of the array_keys method lose performance?

First way:

//For loop
$aggregateDataPerSessions[$gameSession['game_session_id']] = $gameSession;
$sessionIds[] = $gameSession['game_session_id']
//End loop

Second way:

//For loop
$aggregateDataPerSessions[$gameSession['game_session_id']] = $gameSession;
//End loop
$sessionIds = array_keys($aggregateDataPerSessions);

According to the test;
its up to Php version and there is no big diff
https://3v4l.org/3RAU1

enter image description here

2

Answers


  1. First method is more efficient than the second one as it avoids another loop to get the keys. However, in terms of asymptotic complexity, they both have same time complexity which is O(n) where n is the size of the array.

    All in all, you could use either of the 2 approaches as the difference is pretty negligible. However, to answer the question, first method takes lesser time than the second as it avoids one extra looping that second method does with array_keys().

    Login or Signup to reply.
  2. Using built-in functions is usually faster than doing the same using a loop. PHP source code is often optimized to handle such operations very efficiently.

    array_keys() is more efficient than manually assigning the values in a loop. There are a couple of reasons for this, but the main one is just that array_keys is very fast. Pushing the elements in a loop has the disadvantage of resizing the hash table, assigning new variables and a few other things.

    If you can, try to always use built-in functions as they should be magnitudes faster than manual approach.

    A non-scientific benchmark

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search