DEV Community

Discussion on: Capitalize the first letter of every word

alexanderjanke profile image
Alex Janke

I added your function to the benchmark site linked by @aminnairi
Benchmark hello world

Regex seems to performance the fastest... mostly. I'm not really sure how that site samples it's benchmark but it seems awfully fast, meaning few iterations? Having done roughly 30 iterations by hand your regex seems to be ~5-10% faster than the split-map-join. Sometimes the split-map-join is faster though, by a small margin. This is for "hello world" though. Once you start to use longer sentences, your regex becomes the clear winner by a huge margin (roughly 30-40% faster).
Benchmark with longer sentence

willsmart profile image

Hey thanks for that, that's awesome!

One nice thing about the regex way is that it targets the letters it needs to capitalize. I added test cases for an already capitalized sentence and toTitleCase gets a 400% speedup compared to the non-capitalized sentence (since it won't call toUpperCase if it doesn't need to). The others didn't get any speed up (their code could be tweaked, but I don't think there's a way to get such a boost).
Benchmark here