c# 4.0 - Does the C# compiler hoist variable declarations out of methods called within loops? -
i have method calls helper method within for
loop. helper method contains relatively expensive variable declaration , definition involves reflection (see below.) i'm wondering if compiler can counted on inline method call , hoist declaration , definition out of loop, or if need refactor method in order guarantee definition statement isn't executed each iteration.
private class1[] buildclass1arrayfromtestdata() { var class1count = int.parse(testcontextinstance.datarow["class1[]"].tostring()); var class1s = new list<class1>(class1count); (var c = 0; c < class1count; c++) { class1s.add(buildclass1fromtestdata(string.format("class1[{0}]", c))); } return class1s.toarray(); } private class1 buildclass1fromtestdata(string testcontextname) { datacolumncollection columns = testcontextinstance.datarow.table.columns; var class1fields = typeof(class1).getfields(); var class1object = new class1(); foreach (var field in class1fields) { var objectcontextname = string.format("{0}.{1}", testcontextname, field.name); if (!columns.contains(objectcontextname)) continue; // assume fields of type "string" simplicity field.setvalue( class1object, testcontextinstance.datarow[objectcontextname].tostring() ); } return class1object; }
update:
here alternative i'm envisioning, clarification purposes:
private class1[] buildclass1arrayfromtestdata() { var class1count = int.parse(testcontextinstance.datarow["class1[]"].tostring()); var class1s = new list<class1>(class1count); // moved buildclass1fromtestdata() datacolumncollection columns = testcontextinstance.datarow.table.columns; var class1fields = typeof(class1).getfields(); (var c = 0; c < class1count; c++) { class1s.add(buildclass1fromtestdata(string.format("class1[{0}]", c)), columns, class1fields); } return class1s.toarray(); } private class1 buildclass1fromtestdata(string testcontextname, datacolumncollection columns, fieldinfo[] class1fields) { var class1object = new class1(); foreach (var field in class1fields) { var objectcontextname = string.format("{0}.{1}", testcontextname, field.name); if (!columns.contains(objectcontextname)) continue; // assume fields of type "string" simplicity field.setvalue( class1object, testcontextinstance.datarow[objectcontextname].tostring() ); } return class1object; }
the compiler won't such thing, because wouldn't optimization, change meaning of code. calling function once not same thing calling multiple times, , compiler allowed changes don't alter effects of program when observed same thread. cannot detect whether function pure or not.
as side note, compiler won't inline function calls. it's job of jit.
Comments
Post a Comment