I’ve recently had a chance to spend some time working on improving Android app performance which brought some of the memories of dealing with one of the least suitable programming languages for any environment that cares about efficiency - Java. Well, you may argue that these days all cool kids are using Kotlin for Android development and while that may be true, unfortunately, under the hood it’s still the same performance hostile environment that is always looking for ways to annoy your users with janky experience.
One of the first lines of utility function code I’ve seen was responsible for case-insensitive equality comparison
Leaving aside a sketchy assumption about string locales, that’s true for now, but may be easily invalidated without no notice from compiler, there is a performance issue here - toLowerCase returns a new string, which in addition to lowercase transformation results in memory allocations - something we really want to avoid.
There is also a big algorithmic issue with this code - it uses O(N+M) time even at the best case, since even if first characters do not match, toLowerCase of both strings uses O(N+M) time and space. If we process string characters one-by-one we can return as soon as we encounter a mismatch - this still has O(N+M) worst case time complexity, but has O(1) best-case time and O(1) worst case space complexity. Fortunately, we don’t even have to write this ourselves - both Java and Kotlin have case-insensitive comparison
It’s concise, readable, faster and correct, as it doesn’t assume anything about locales. How much faster?
I was too lazy setup Kotlin development environment locally to run benchmarks, so I’ve used their playground.
Even such primitive benchmark is sufficient to showcase 2-3X speedup. Not bad, for a code that is also nicer and correct.