To answer your question ,
"How does the effectiveness of these cases change regarding the implementation of the map?"
The difference in performance is negligible.
Comment on the comment
"In the second snippet, I don't like the fact that the value is declared with a wider scope."
Ok, you shouldn't. You see, there are two ways to get null returned from the map:
- The key does not exist OR
- The key exists, but its value is null (if the map implementation allows null values ββsuch as HashMap).
Thus, two scenarios can have different results if the key existed with a zero value!
EDIT
I wrote the following code to test the performance of two scenarios:
public class TestMapPerformance { static Map<String, String> myMap = new HashMap<String, String>(); static int iterations = 7000000; // populate a map with seven million strings for keys static { for (int i = 0; i <= iterations; i++) { String tryIt = Integer.toString(i); myMap.put(tryIt, "hi"); } } // run each scenario twice and print out the results. public static void main(String[] args) { System.out.println("Key Exists: " + testMap_CheckIfKeyExists(iterations)); System.out.println("Value Null: " + testMap_CheckIfValueIsNull(iterations)); System.out.println("Key Exists: " + testMap_CheckIfKeyExists(iterations)); System.out.println("Value Null: " + testMap_CheckIfValueIsNull(iterations)); } // Check if the key exists, then get its value public static long testMap_CheckIfKeyExists(int iterations) { Date date = new Date(); for (int i = 0; i <= iterations; i++) { String key = Integer.toString(i); if(myMap.containsKey(key)) { String value = myMap.get(key); String newString = new String(value); } } return new Date().getTime() - date.getTime(); } // Get the key value, then check if that value is null public static long testMap_CheckIfValueIsNull(int iterations) { Date date = new Date(); for (int i = 0; i <= iterations; i++) { String key = Integer.toString(i); String value = myMap.get(key); if(value != null) { String newString = new String(value); } } return new Date().getTime() - date.getTime(); } }
I ran it and this was the result:
Key Exists: 9901 Value Null: 11472 Key Exists: 11578 Value Null: 9387
So, in conclusion, the performance difference is negligible.
source share