开发者

Micro-optimisation of keys versus in_array() in PHP

开发者 https://www.devze.com 2023-02-22 14:31 出处:网络
So you have the option to structure an array as you please knowing that a few lines further down in your code you are going to need to check for the existence of a value in that array. The way I see i

So you have the option to structure an array as you please knowing that a few lines further down in your code you are going to need to check for the existence of a value in that array. The way I see it you have at least two options:

$values_array = array(
    'my_val',
    'my_val2',
    'and_so_on',
);

if(in_array('my_val', $values_array)) {
    var_dump('Its there!');
}

Or you could use an associative array and use the keys to contain your value:

$values_array = array(
    'my_val'    => '',
    'my_val2'   => '',
    'and_so_on' => '',
);

if(isset($values_array['my_val'])) {
    var_dump('Its there!');
}

Which method would you pick and why? Would you be solely aiming to reduce process time or also minimise the amount of memory used?

Perhaps you wouldn't use my two puny methods and have another awesome way to solve this simple problem.

This is a theoretical question with no real world application in mind, but there could be thousands of options i开发者_StackOverflow中文版n the array. It is a speculative question really to see which method is considered better by everyone. Whether it be considered so for readability, speed or memory usage reasons.


Really? Use the variant, that fits better to your and your applications needs. Especially with so less elements, it is far out of scope of measurement.

But there is a real semantic difference between both. The first one defines a list, the second one defines a map. If $array should represent a list, use the first one, if it should represent a map, use the second one (obvious, huh? ;)).

At all: Let never such micro optimization approaches influence your application design.


Code readability and maintainability always trump optimisation.

The developer-time wasted trying to untangle code that is deliberately obtuse just to save a few microseconds generally outweights the value of those saved microseconds.

If you're writing something where execution speed really makes enough of a difference to care about this sort of thing, then PHP (or indeed any interpreted language) is probably the wrong language. And if you are trying to optimise PHP code, there's almost certainly better places to start than this.


Well, I'd tend to the second one, as I have a feeling that this one is more optimal. And I am using it quite often.
However, if it become a bottleneck, I'd measure alternatives.

Anyway, I would never think of these thing while my arrays being relatively small - up to several hundreds items. And I would try to avoid such searches on heavy arrays at any cost anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号