# getting-started


04/02/2022, 4:09 AM
When calling
String.replace(String, String)
does it ever make sense to wrap it with
if (String.contains(String))
for example if the occurrence is very unlikely? Or perhaps it depends on the target architecture?


04/02/2022, 7:38 AM
It's usually a safe bet that the standard library implementation is as efficient as anything you could come up with yourself. Even if it's not, I think the readability benefits of sticking to standard functions generally outweigh any performance benefits you might be able to extract. And the standard library can always be improved in future, which you might lose the benefit of if your code is littered with custom implementations.
👍 1


04/02/2022, 8:14 AM has a fast-path for the no-match case. you're not going to improve upon it by wrapping it in another conditional.
👍 1


04/02/2022, 8:14 AM
@Sam that’s true although there is no way the standard library can know that the substring being replaced is unlikely or not. This would be domain-specific knowledge.

Stephan Schroeder

04/02/2022, 9:13 AM
your code just means that the string to replace has to be found two times, if it's present. If the string isn't present, the whole string still has to be parsed by your contains-check, so it's not faster either. So your check can only slow down things.


04/02/2022, 10:32 AM
It makes sense to do so, if you have a measurable performance problem that goes away with the change. Never try to micro-optimize up-front. 1. Make the code work, optimally with tests 2. Make the code nice by refactoring (here tests help to ensure you don't break it) 3. Optimize performance or memory usage if and only if you have a measurable problem. 80 % of the runtime of a program is spent in 20 % of the code and there is no point in optimizing the other 80 % while sacrificing readability. For example if you have a function that is called one a day, it's probably unimportant whether it runs 1 minute or 1 second. But if the same function of called once per second, you have a problem you needed to fix.
🙌 1