I benchmarked the following methods
'while loop' is the "1 while..." method.
'reverse' is the Andrew Johnson method.
'lookahead' is the stefp method.
'manual' is the one using substr.
'le3manual' is the one using substr with an initial check to make sure there are more than three digits.
| Number: | 3 | 2489 | 8x10^8 | 8x10^13 |
| while loop: | 869k/s | 60k/s | 33k/s | 18k/s |
| reverse: | 465k/s | 65k/s | 47k/s | 34k/s |
| lookahead: | 571k/s | 54k/s | 34k/s | 22k/s |
| manual: | 270k/s | 139k/s | 95k/s | 61k/s |
| le3manual: | 1000k/s | 135k/s | 91k/s | 59k/s |
Nk/s = N thousands of completed commafications per second
Basically it looks like the substr method, with the <=3 clause, obliterates the competition. I feel dirty saying it, but looks like a one-liner regexp is not the best solution.
(My test script is available
here)