13

In terms of performance, which is the better option?

While in object:

Case #1

public function test( $array ) {
    return array_map( array( $this, 'do_something_to_element' ), $array );
}

Case #2

public function test( $array ) {
    $return = array();
    foreach ( $array as $value ) {
        $return[] = do_something_to_element( $value );
    }
    return $return;
}

There are other uses of course and many many examples can be populated. I've seen comments that while in an object, array_map is slower than foreach loops.

In general is the array_map/array_walk functions faster to execute than the foreach loops in similar needs?

4
  • Go to eval.in and test it? Commented Aug 25, 2014 at 8:19
  • 1
    Why don't you benchmark it? It may theoretically also vary dramatically between different PHP versions, so it's hardly a constructive question. Few performance questions are. Commented Aug 25, 2014 at 8:20
  • 1
    Given that you're not using the keys of the array, why not compare these two approaches to a simple for loop, too? for loops tend to outperform foreach, and seeing as loops are constructs, and not function calls, I'd expect them to outperform array_map Commented Aug 25, 2014 at 8:22
  • You can test one of the solution given by PHP code's performance test. Like says deceze, performance can change following your PHP version. Commented Aug 25, 2014 at 8:24

2 Answers 2

9

For the record (php 7.4 + 64bits + windows)

https://github.com/EFTEC/php-benchmarks/blob/master/benchmark_arraymap_foreach.php

  • foreach = 0.10213899612427
  • array_map = 0.18259811401367
  • array_map (static) = 0.18230390548706
  • array_map (calling a function) = 0.17731499671936

Foreach is still faster but also if we use a static function or not, it doesn't make any difference:

    $result = array_map(function ($number) {
        return $number * 10;
    }, $numbers);
    $result = array_map(static function ($number) {
        return $number * 10;
    }, $numbers);
Sign up to request clarification or add additional context in comments.

Comments

6

I tested this on a Symfony project just now, had to Google because it seems so significant. Script went from 160ms using foreach() to 260ms using array_map(). Considering the size of the application thats quite a large increase from a single method call.

1 Comment

Can you post the code under test, the actual test, and how you benchmarked this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.