Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster way to get a value from a JSON array than foreach?

Tags:

json

php

I have a JSON array like this:

[
  {"location":"1","distance":"25.75206"},
  {"location":"2","distance":"21.49343"},
  {"location":"3","distance":"24.13432"}
]

Right now I am doing a foreach with every $location to get the corresponding data.

$locations = json_decode($locations, true);

foreach ($locations as $key => $value) {
  if ($value['location'] == $location) {
    $distance = $value['distance']; 
  }
}

The problem is, the arrays can be very big with several thousand items, so doing a foreach is quite resource intensive and can slow things down.

Is there any more "direct" and less resource intensive way of getting each corresponding value?

like image 328
moo moo Avatar asked Mar 05 '23 19:03

moo moo


2 Answers

foreach is quite resourced intensive and can slow things down because it copies input array and works with this copy. If you want to avoid this behavior you can use access by a pointer. For example, you can use reset, next and current construction for working with a pointer

$value = reset($locations);
while ($element !== false)  {
    if ($value['location'] == $location) {
        $distance = $value['distance']; 
    }
    next($locations); 
    $value = current($locations);
}

And of course, you can use a pointer in foreach. For example:

foreach ($locations as $key => &$value) {
  if ($value['location'] == $location) {
    $distance = $value['distance']; 
  }
}
like image 55
Maksym Fedorov Avatar answered Mar 08 '23 00:03

Maksym Fedorov


I am not a PHP guy, I don't know if this applies here, but in general (not necessarily in all cases) if you have a list of something and know the size or can detect the end you can iterate through it and access each item with the index number (ie, list[0], list[1], list[2], etc). Iterating through a list in this way is typically faster, but again I don't know PHP and perhaps that isn't true in this situation.

I'll also add, while I don't know the environment in which you are implementing this, in many cases it isn't really going to matter. foreach implementations in many languages are often very optimized.

like image 32
Davenporten Avatar answered Mar 08 '23 00:03

Davenporten