I am new to Java and I am trying to learn about optimizing code to make it production ready. I have the following code below. I would like to know how I could optimize it. I thought by using a small snippet of could, it would be a good way to learn.
Some points:
- The function would be run many times to it needs to be fast.
- The input is unconstrained since it might come from a user or from a file. Is there a way to deal with this so not exceptions are thrown? I was thinking of using a regular expression.
- Is there anything else I need to do to make it production ready? e.g. unit tests. If so, what would be the best way to do this?
- I am assuming that the string to be searched is not very long.
- When I say optimization, I mean doing things like replacing the
+
operator with something faster is it can effect memory and performance, etc.
public String strReplave(String originalStr, String oldStr, String newStr) { int start = 0; while ((start = originalStr.indexOf(oldStr, start)) > 0) { originalStr= originalStr.substring(0,start) + newStr+ originalStr.substring(start + oldStr.length()); start += newStr.length(); } return originalStr; }
Thanks for your help and if you need me to clarify anything please let me know.
String replace(CharSequence target, CharSequence replacement);
?String
s implementCharSequence
, so you could use that likeString ns = "Hello world".replace("world", "people");
\$\endgroup\$