Surprising CLR / JIT? behaviour - deferred initialization of a local variable

ぃ、小莉子 提交于 2019-12-02 11:48:48

问题


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.



来源:https://stackoverflow.com/questions/9615943/surprising-clr-jit-behaviour-deferred-initialization-of-a-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!