Ordinal Suffix for a Number which is a String in JSPosted on: December 21, 2012

I encountered a scenario on my latest project where I received a date as a string (ie: 2012-12-21) and needed to display it as 21st December. This had me first trying my own hand at doing this, and - thinking that there could possibly be a more efficient way of doing this

  • I googled it. There wasn't much out there to be honest, and probably within reason since the main thing I came across seemed to be the best.

I know this because I set up a jsperf test with my own implementations along with the common ones I found.

I did come across something interesting though. You'll notice that I've set up a teardown that increments the num variable after each loop for each test. Removing this gave me completely different results. I decided to try manually going from 0 through to 25 and see what happens (purely out of an admittedly very nerdy interest). Below is a summary of what I found (see this gist for all the boring details):

Between 0 and 19: There was an even split between the Regex and < ternary tests. The slowest test hands down was the || ternary test, except on 0 and 7 (oddly) where Regex was the slowest. Between 20 and 24: || ternary was the fastest - the test that ran slowest between 0 and 19 I might add! Between 20 and 25: The slowest was almost an even split between Regex and Slice. Again, interesting that Regex was among the quickest between 0 and 19.

At the end of the day, it's all a bit boring really and the amount of time saved is absolutely miniscule. My advice is and will always be that if you're looking at saving time, there are tons of other things you could be doing to improve performance first before trying to shave off microseconds. I did this purely to appease my rather nerdy curiosity.