Tales of an IT Nobody

devbox:~$ iptables -A OUTPUT -j DROP

Add “th” (“nd”, “st”) to a number … painlessly – Part 2 April 26, 2011

So in the previous post I posted my recipe for adding rank suffixes to numbers.

Sometimes – a simple problem can be frustratingly goofy to solve. I took a lazy shortcut by passing the number through mktime – then to date to do it for me.

After analyzing what I came up with – it occurred to me that my final approach could be streamlined even better.

Logically we add ‘st,nd,rd’ to numbers 1-3 in all circumstances except when they’re in what I call an ‘eleventh’ verbal range – meaning ‘111’, ‘213’ – we simply do ‘th’.

Since I’ve already determined the wrap around (mod 10) – I gathered maybe just a straight up switch statement would be faster in the big picture …

So here’s the 2nd rendition of my function:

It’s longer for sure – but when run through a simple benchmark:
10 passes of a 100,000 iteration loop the results are pretty clear on how mktime+date can drag it down, it’s not the most scientific method but the gap is big enough to call the results conclusive:

Version 1 (With mktime+date)
Time: 7.79 seconds

Version 2 (See above – switch)
Time: 4.81 seconds

For some reason – solution #2 doesn’t feel as ‘cool’ as the first solution; I like the hackish appeal of it, but there seems to be more elegance in the simplicity, with more truth in it’s nature.

Categories: php programming

Leave a Reply

Your email address will not be published. Required fields are marked *