0

I am trying to figure out what way of getting to the same result is better, as in faster, less memory usage.

$resp = [];
foreach($data as $val){
  $resp[$val] = $val;
}

return array_values($resp);

vs

$resp = [];
foreach($data as $val){
  if(!\in_array($val, $resp, false)){
      $resp[] = $val;
  }
}

return $resp;

I was thinking that the first option would use more memory since it will have values as keys,

but the second option would use more cpu since it will have to check in_array for an ever growing array.

Any ideas?

The result should be

[
  0 => 'no dup data',
  1 => 'no dup data 1',
  ...
]
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337
  • Well why don't you test it yourself and then show us your own study? – Martin Dec 17 '18 at 19:47
  • 1
    Are you just trying to get the same as `array_unique()`? – Nigel Ren Dec 17 '18 at 19:47
  • `microtime(true)` and `memory_get_usage()` – AbraCadaver Dec 17 '18 at 19:52
  • @Martin is not the same question as ur dup – Patrioticcow Dec 17 '18 at 19:58
  • Why not? You're using far less efficient queries than `array_unique`, you state you want to use `faster and more efficient` methods so the answers to the dupe give you those abilities. – Martin Dec 17 '18 at 20:01
  • 1
    You may like to take a look at [my test, here](http://sandbox.onlinephpfunctions.com/code/2386f1144a3633e5cc9676a30d379bf7b4e64c69). My testing timing show that [this answer](https://stackoverflow.com/a/53822096/3536236) is *orders of magnitude* faster than the other methods – Martin Dec 17 '18 at 20:07
  • performance and memory usage are not inclusive, so "better" would be subjective to what you want to accomplish. For all intents and purposes `array_unique()` https://3v4l.org/nIah0/perf#output will accomplish your desired results quickly but [use more memory than `array_values`](https://3v4l.org/MQghg/perf#output). An alternative would be to use [`array_flip` twice](https://3v4l.org/jZ4Va/perf#output) or with `array_keys` Which will swap the index to the value, and back again, but is faster and uses less memory. – Will B. Dec 17 '18 at 20:11

0 Answers0