0

I wrote this tiny function a while ago to make a unique id based on passed arguments. My question is, if there is a better (performance) way to solve that.

function id_make(/* POLYMORPHIC */)
{
    return md5(serialize(func_get_args()));
}

echo id_make(__FILE__, 'something', ['item' => 'some_content']);
hakre
  • 193,403
  • 52
  • 435
  • 836
n00b
  • 16,088
  • 21
  • 56
  • 72
  • performance for what? less storage space? less computational time? – Marc B May 27 '13 at 15:09
  • '_ _FILE_ _' itself is just a file name but perhaps it would make more sense to give it a context such as the contents of this file. – Ja͢ck May 27 '13 at 15:14
  • @Jack yes, that's what i'm doing sometimes. Usually like: id_make(md5_file(__FILE__), 'some other identifier'); – n00b May 27 '13 at 15:28

3 Answers3

1

For the given function signature, there's not much to improve - it's 3 chained function calls in a row that do precisely what you want them to do, so nothing to optimize or strip there.

Given that the 3 function calls all more or less boil down to native compiled functionality internally, I also don't think there's an alternative approach possible that would give the same level of flexibility, without creating possible collisions.

So no, nothing really to improve here in this function. The outside code can probably use some optimizations if you need this kind of flexible hashing.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
1

crc32 seems to be a bit faster then md5 (http://www.php.net/manual/en/function.crc32.php)

json_encode() is also a bit faster then serialize().

gries
  • 1,135
  • 6
  • 29
  • 1
    `json_encode` is also [less flexible than `serialize`](http://stackoverflow.com/a/5351788/1729885) and will slightly increase chance of collisions. Not really probable of course for any expectable use case. – Niels Keurentjes May 27 '13 at 15:14
1

I guess that the performance issue occurs when trying to pass rather large objects as arguments?

I don't know the purpose of your script but maybe this might help. Maybe you should loop trough the arguments and when it is a object you could replace it with it's hash. See: http://php.net/manual/en/function.spl-object-hash.php

But because as I said I don't know the purpose, you should note that the same hash may be re-used when the object is destroyed.

NLZ
  • 935
  • 6
  • 12