replace()
is more efficient in cases where there is no key being used in it. It can only replace a value from an existing key, executes nothing if it does not have the key. Already the put()
will place a value there, if the key exists it will be equal to the replace()
, but if it does not exist you will have to create the key on the map, which has extra cost.
But performance should not be considered, the important thing is the semantics that wants to give, they give different results in certain circumstances, as shown above, so I use what you need.
In this example the test makes no sense (obviously that the first will be slower, it does much more and gives different result to the second, it makes no sense to compare these two things). If you only want to change the value if the key exists and not create a new one, use the replace()
. To get the same result with put()
would have to do so:
if (Lista.containsKey(teste)) lista.put(teste, outro);
which is the same as:
lista.replace(teste, outra);
Documentation.
The proper test would be thus:
import java.util.*;
class Main {
public static HashMap<String, String> lista = new HashMap<>();
private static void Put(String teste, String outra) {
for (int i = 0; i < 100000; i++) if (lista.containsKey("antonio")) lista.put(teste, outra);
}
private static void Replace(String teste, String outra) {
for (int i = 0; i < 100000; i++) lista.replace(teste, outra);
}
public static void main(String[] args) {
long inicio = System.currentTimeMillis();
Put("antonio", "antonio");
System.out.println("Put: " + (System.currentTimeMillis() - inicio) + " ms");
inicio = System.currentTimeMillis();
Replace("antonio", "antonio");
System.out.println("Replace: " + (System.currentTimeMillis() - inicio) + " ms");
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site
– Maniero