I just want to find some fastest set bits count function in the php.
For example, 0010101 => 3, 00011110 => 4
I saw there is good Algorithm that can be implemented in c++. How to count the number of set bits in a 32-bit integer?
Is there any php built-in function or fastest user-defined function?
You can try to apply a mask with a binary AND, and use shift to test bit one by one, using a loop that will iterate 32 times.
You can also easily put your function into PHP style
My benchmarking code
Benchmarking result:
benchmark (NumberOfSetBits()) : 1.429042 milleseconds
benchmark (substr_count()) : 1.672635 milleseconds
benchmark (getBitCount()): 10.464981 milleseconds
I think NumberOfSetBits() and substr_count() are best. Thanks.
There are a number of other ways; but for a decimal 32 bit integer,
NumberOfSetBits
is definitely the fastest.I recently stumbled over Brian Kernighan´s algorithm, which has
O(log(n))
instead of most of the others havingO(n)
. I don´t know why it´s not appearing that fast here; but it still has a measurable advantage over all other non-specialized functions.Of course, nothing can beat
NumberOfSetBits
withO(1)
.my benchmarks:
banchmark results (sorted)
Those are the numbers from one of my runs (with PHP 7.0.22); others showed different order within the 3.5 seconds group. I can say that - on my machine - four of those five are pretty equal, and
bitsBySubstrInt
is always a little slower due to the typecasts.Most other ways require a decbin (which mostly takes longer than the actual counting; I marked them with a
*
in the benchmark results); onlyBitsBySubstr
would get close to the winner without that gammy leg.I find it noticeable that you can make
count_chars
3 times faster by limiting it to only existing chars. Seems like array indexing needs quite some time.edit:
preg_replace
versionpreg_match_all
versionI could figure out a few ways to but not sure which one would be the fastest :
PS : if you start with a integer these examples would involve using decbin() first.