replace()
is more efficient in cases where there is no key being used in it. It can only replace a value of an existing key, it performs nothing if it does not have the key. However, the put()
will put a value there, if there is a key it will be equal to 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 you want to give, they give different results under certain circumstances as shown above, so use what you need.
In this example, the test does not make sense (obviously the first one will be slower, it does much more and gives a different result from the second, it does not make sense to compare these two things ). If you only want to change the value if the key exists and do not create a new one, use 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 appropriate test would look like this:
import java.util.*;
class Ideone {
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");
}
}
See running on ideone . And in Coding Ground . Also I placed GitHub for future reference .