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
2
Answers
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 isO(n)
wheren
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()
.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 thatarray_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