2

For a while now I've been using the following code to set a new map. As you can see, I am using curly brackets after I state the data types that the map uses.

Map<String,String> awesomeMap = new Map<String,String>{};

This works perfectly fine as it is. However, while browsing the SalesForce docs for the Map Method I noticed that although they use the same method that I've been using, they also use parentheses in some of the examples. They actually seem to use the parentheses method more often.

Map<String,String> awesomeMap = new Map<String,String>();

Both of these methods seems to do the same thing on the surface. What I'm wondering though is if below the surface one of these methods works better than the other. I will likely stick with the curly brackets for consistency (I can't stand inconsistent code) unless there is a huge performance difference.

Just curious.

8

With no parameters, new Map<KeyType, DataType>() and new Map<KeyType, DataType> { } have identical behavior. I tested a loop of 50,000 new maps of each and grabbed the timestamps from the logs, and they were almost consistently 64ms for 50,000 maps (we can't account for server load, however, so this performance may vary); approximately 0.001ms to create a new map either way.

The difference, however, is that each form has a different purpose. The parenthetical version is used to create a map from a list of SObject records or another map. They look like this:

Map<String, String> a = new Map<String, String>();
Map<String, String> b = new Map<String, String>(a);
Map<Id, SObject> c = new Map<Id, SObject>([SELECT Id,Name FROM Contact]);

The bracketed version is used to instantiate a map with values:

Map<String, String> a = new Map<String, String>{
  'a' => '1',
  'b' => '2',
  'c' => '3' };
| improve this answer | |
  • That makes a lot of sense! I'm typically just populating the maps after the fact through for loops and .put() so I haven't had to mess around with it all that much. Thanks for the clear, concise answer. :) – VictorKilo Jul 25 '13 at 18:52
  • I especially appreciate your thoroughness - even going as far as to run timing tests. – VictorKilo Jul 25 '13 at 22:29
1

If you want to instantiate an empty map, use the parenthesis version. This way it is clear you are calling the Map constructor and are consistent with all non-generics.

The curly bracket version is for instantiating a map with predefined elements. It works either way because in your case you are instantiating a map with 0 elements.

Map<Integer, String> myMap = new Map<Integer, String>
  {
    1 => 'dog',
    2 => 'cat'
  };
| improve this answer | |
  • You're almost correct. The parenthetical version can be used to copy a map or populate a map from a list of records. – sfdcfox Jul 25 '13 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.