Surprising CLR / JIT? behaviour - deferred initial

2019-03-02 13:56发布

问题:

I have just encountered something quite bizarre running an app in Debug mode (VS 2008 Express, Any Cpu). I would appreciate if someone enlightened me as to what is happening here?

// PredefinedSizeGroupMappings is null here
Dictionary<string, int> groupIDs = PredefinedSizeGroupMappings ?? new Dictionary<string, int>();

// so groupIDs is now initialized as an empty Dictionary<string, int>, as expected

// now: PredefinedSizesMappings is null here - therefore I expect sizeIds
// to be initialized as an empty dictionary:
Dictionary<string, string> sizeIds = PredefinedSizesMappings ?? new Dictionary<string, string>(); 

// but at this point sizeIds is still null! :O That's what debugger shows.
var groupsReport = new AutomappingReportArgs();

// only once we get here - it's suddenly not... The debugger shows: "Count = 0"
var sizesReport = new AutomappingReportArgs();

The AutomappingReportArgs class has no connection whatsoever to the sizeIds variable, although its constructor does alocate a number of dictionaries:

public AutomappingReportArgs()
{
    ChangedNames = new Dictionary<string, KeyValuePair<string, string>>();
    CreatedAfterRename = new Dictionary<string, string>();            
    Existing = new Dictionary<string, string>();
    Created = new Dictionary<string, string>();
    Failed = new Dictionary<string, string>();
}

I guess it must be some sort of compiler or CLR optimization, but I would like to know the mechanism of it in more detail. What is the reason for this "deferred initialization"?

And why is it inconsistent, why does it work straight away for Dictionary<string, int>, but not for Dictionary<string, string>? Is it because the compiler can't see any Dictionary<string, int> initialization ahead, so it can't put it aside for later?

回答1:

This is pretty standard behavior when you debug optimized code. Unlikely to be the case here. Likely to be a bug in the debugger instead. There was an important post SP1 hotfix for VS2008 that fixed a number of debugger problems.

You'll find the link to the hotfix in this answer. Not so sure how applicable the hotfix is to the Express Edition, you should be okay but I can't guarantee it.