I had to do some string stripping in one of my apps which was a bit performance sensitive. I ended up benching multiple approaches to see the speed differences. The results are not that suprising.
So, the next time you want to strip prefixing stuff, use pattern matching :)
Based on the comments by @Matt Widmann and @Peter I did a quick test of replacing the tail of the string using the following code:
The results for this are:
This led be to look at the actual Elixir code for
replace_suffix which is:
I tweaked the benchmark code a little to run each replace a 1000 times to remove the “too fast” warning.
For reverse string removal from the end,
replace_suffix is the fastest which makes sense.
However, for removing the prefix,
pattern_match_bytes seems to be the fastest. But, it isn’t really truly correct. Because in my instance, I know for sure that the prefix is present.
So, the second best performance for which is
pattern_match is 6x better than the current
It may be because I am using OTP 20? I’ll run this on other versions of OTP to compare results. And, if the results are cosistent, will create PR on elixir to change the default implementation.