2

what algorithm does array sum uses to make it much faster than some looping through?

Is it prefix sum / suffix sum or something else?

2
  • 1
    I must be a linear algorithm too, but intrinsic PHP functions (i.e. all functions available in PHP directly) are executed faster Commented Jul 29, 2014 at 13:25
  • 1
    Basically the same algorithm that you'd implement if you wrote loop to do it, but it's executing as straight compiled C code, not PHP Commented Jul 29, 2014 at 13:27

2 Answers 2

5

Algorithm is plain: just iterate through array and produce summation of elements. That's it. In terms of algorithm there's nothing more that could be said about it. Obviously, you'll have complexity as O(n) for it.

However, PHP array_sum() is a compiled C code, thus, is will be faster than user-land function. Also, if you're interested in how it works internally, you may check array_sum() implementation:

for (zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos);
    zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS;
    zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos)
) {
    if (Z_TYPE_PP(entry) == IS_ARRAY || Z_TYPE_PP(entry) == IS_OBJECT) {
        continue;
    }
    entry_n = **entry;
    zval_copy_ctor(&entry_n);
    convert_scalar_to_number(&entry_n TSRMLS_CC);
    fast_add_function(return_value, return_value, &entry_n TSRMLS_CC);
}

(I've left only loop part itself). There's also fast_add_function() asm optimization, you can check out it's implementation here.

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

1 Comment

You win, master ninja.
1

It uses the same algorithm as if you were to write a loop in PHP (that is, the O(n) linear solution), except in most cases since it's native code (written in i.e. C) and not interpreted, it runs directly on the CPU instead of via a virtual machine (which is between 10 and 100 times slower).

Comments

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.