0

Which of the following two is faster? Only difference being an explicit array() initialization.

$fields['a'] = 1;
$fields['b'] = 2;

vs.

$fields = array();
$fields['a'] = 1;
$fields['b'] = 2;
2
  • 3
    Is this the slowest part of your code? Commented Jan 8, 2013 at 8:36
  • 2
    It does not make sense if you don't initialize it. Make codes logical. Commented Jan 8, 2013 at 8:37

3 Answers 3

6

Instead of worrying about performance, you should be writing sensible, readable code. This is much better:

$fields = array();
$fields['a'] = 1;
$fields['b'] = 2;

compared to this:

$fields['a'] = 1;
$fields['b'] = 2;

You might save few fractions of a second of a machine; but you will definitely waste valuable time of the person who reads your code. He/she will will have to scroll through your code to locate where $fields is initialized and if it already contains some values.

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

1 Comment

When I have situations like this I prefer: $fields = array('a' => 1, 'b' => 2);. It saves keystrokes and is easy to understand, IMO.
2

Caution: These numbers vary from hardware to hardware

0.0000109672546386720 seconds without array();

VS

0.0000090599060058594 seconds with array(); (faster!)

But better with array(); Seems more logical.

1 Comment

@MarkBaker i did average of 100 Tests
2

Micro Benchmark does not make sense just focus on more readable code but for education purpose this is the fastest

$array = array('a' => 1,'b' => 2); // fastest PHP 5.4
$array = ['a' => 1,'b' => 2]; // fastest PHP 5.5

See Benchmark

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.