Recently, I have been really involved with Project Euler, and frequently encountered many large numbers that PHP was unable to deal with using it’s core functions. However, PHP has an extension called BC math, which can process numbers of any size. To add using BC math, you would use:

$sum = bcadd($num1, $num2);

You can subtract, multiply, divide, and etc, using bcsub, bcmul, bcdiv, respectively. However, there are many drawbacks to using BC Math.

After doing several benchmarks, it seems as if BC math was 20 times slower than PHP’s core math functions. Here are the benchmark scripts:

**Core Math Functions**

<?php $t = microtime(1); $i = 0; while($i < 1000000) { $i++; } echo microtime(1) - $t; ?>

**BC Math**

<?php $t = microtime(1); $i = 0; while($i < 1000000) { $i = bcadd($i, 1); } echo microtime(1) - $t; ?>

**Summary**

It seems interesting how BC math is so many times slower than the regular math functions. Considering these benchmark results, it’s much better to use PHP’s core math functions than to use BC math, unless dealing with numbers too big to be dealt with by the normal math functions.

Good to know that basic (aka “core”) math is faster and I had never heard of “bc{whatever}()” until today… now I have a useless function in my head…

BC library is slower because it’s built to provide better precision when handling float numbers, not necessary required only for big numbers. http://stackoverflow.com/questions/3148937/compare-floats-in-php

<?php

$a = 0.17;

$b = 1 - 0.83; //0.17

`echo "$a == $b (core comp oper): ", var_dump($a==$b);`

echo "$a == $b (with bc func) : ", var_dump( bccomp($a, $b)==0 );

`Will return:`

0.17 == 0.17 (core comp oper): bool(false)

0.17 == 0.17 (with bc func) : bool(true)