20

Is there a way or a resource for finding the time and space complexity of the Array implementation in PHP other than calculating it by hand?

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. - php.net

From what I can tell it would seem that it has the general complexity of a map

1

3 Answers 3

21

Because it acts like a hash table, you will have O(1) time when accessing an element by a key.

If you are looping through the array, naturally you will have O(n) time.

If you have time, you can actually check out PHP's implementation of array here

Sign up to request clarification or add additional context in comments.

Comments

7

Accessing and iterating is describe by @Mike-Lewis so far

  • Setting a value: O(1)
  • Append: O(1) (Its the same as setting a value to the key "length")
  • Prepend: O(n) (Its a guess, but should fit, because it should rewrite the existing keys)
  • Unset: O(1)

Anything missed?

1 Comment

- Insert: O(n) (It's guess, because the existing values which come after the new one have to be rewritten)
1

In addition to what @Mike Lewis said, I would add, that one array element in PHP occupies minimum of 52 bytes (proof)

3 Comments

Just for the record, as of 2020 for PHP 7.3 this amount is about 2.5 times less. More about this.
Anyone knows the memory performance of SplFixedArray compared to array?
How about php8, has this reduced in memory usage?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.