When calling `String.replace(String, String)` for ...
# announcements
m
When calling
String.replace(String, String)
for an unlikely replacement, does it ever makes sense to wrap in a
CharSequence.contains(CharSequence)
call, for efficiency?
v
Never do micro-optimisations up-front. 80% of the runtime of a program is spent in 20% of the code. There is no point in optimizing the remaining 80% too much. • make your code work like you want it • then make your code nice be doing refactorings • then make it fast where necessary, i. e. where you have a proven performance problem
☝️ 2
m
Of course that’s true, but I’m just curious 🙂. Out of interest,
"hello".replace("x", "y")
returns the same
"hello"
instance whereas
"hello".replace("e", "e")
returns a different one.
v
Ok, then my answer is "I have no idea, run a benchmark" 😄 But I guess it makes a slight difference, looking at the implementation. But implementations could also change or be different on different platforms.
Out of interest, 
"hello".replace("x", "y")
 returns the same 
"hello"
 instance whereas 
"hello".replace("e", "e")
 returns a different one.
I'd say the first one is a slight bug that is totally pointless. The docs say "Returns a new string obtained by replacing all occurrences of the [oldValue] substring in this string with the specified [newValue] string.". But as `String`s are immutable anyway it doesn't make sense to create a new instance for the first case. To have the latter return the same instance it would need an additional check whether both parameters are the same which is useless in 99% of the cases.
m
Obviously the first one can happen when we are not hard-coding the arguments, but anyway the result is good since the same instance is returned. For the second one, it’s not true that it would have to check the arguments, since it could alternatively check the result, although that would be even more ridiculous 🙂
v
Doesn't matter what it checks (parameters would make more sense, because why do the replacing to check the result for equality when you can already check the input). It would be an additional check that is useless in 99% of the cases.
m
I think you would need to run some benchmarks to test for that 99% figure, because some domains might be quite different :)
v
Actually I just assumed that almost noone tries to replace something with itself as it just makes no sense, so the figure is totally made up, yes. :-D
m
Actually, the first scenario is the point of my original question. I would guess 99.99% of the replaces I do are not matching anything (I’m dealing with unknown texts). But I agree the second scenario is unlikely to be relevant.