以本机速度运行动态编译的C#代码如何...?我读过几篇关于编写和编译动态C#代码的文章。比如这篇文章。我知道这可以通过多种方式完成。但是,调用代码调用程序很慢。我做了一个简单的基准测试,它比调用本地方法慢了大约500倍。我想要做的是相当于加载DLL并直接调用其中一种方法(“本机”),这将提供我想要的速度优势。最简单的方法是什么?将动态代码编译成dll然后加载?可以在内存中完成吗?编辑我不关心编译时间。仅执行。编辑2,3这是我写的基准代码:publicstaticintExecute(inti){returni*2;}privatevoidbutton30_Click(objectsender,EventArgse){CSharpCodeProviderfoo=newCSharpCodeProvider();varres=foo.CompileAssemblyFromSource(newSystem.CodeDom.Compiler.CompilerParameters(){GenerateInMemory=true,CompilerOptions=@"/optimize",},@"publicclassFooClass{publicstaticintExecute(inti){returni*2;}}");vartype=res.CompiledAssembly.GetType("FooClass");varobj=Activator.CreateInstance(类型);varmethod=type.GetMethod("执行");inti=0,t1=Environment.TickCount,t2;//varinput=newobject[]{2};//for(intj=0;j<10000000;j++)//{//输入[0]=j;//varoutput=method.Invoke(obj,input);//i=(int)输出;//}//t2=Environment.TickCount;//MessageBox.Show((t2-t1).ToString()+Environment.NewLine+i.ToString());t1=Environment.TickCount;对于(intj=0;j<100000000;j++){i=执行(j);}t2=环境onment.TickCount;MessageBox.Show("Native:"+(t2-t1).ToString()+Environment.NewLine+i.ToString());varfunc=(Func)Delegate.CreateDelegate(typeof(Func),方法);t1=Environment.TickCount;对于(intj=0;j<100000000;j++){i=func(j);}t2=Environment.TickCount;MessageBox.Show("动态委托:"+(t2-t1).ToString()+Environment.NewLine+i.ToString());FuncfuncL=执行;t1=Environment.TickCount;对于(intj=0;j<100000000;j++){i=funcL(j);}t2=Environment.TickCount;MessageBox.Show("委托:"+(t2-t1).ToString()+Environment.NewLine+i.ToString());是的,如果您通过MethodInfo或非特定的Delegate调用,那么它确实会很慢诀窍是:不要那样做。各种方法:如果遇到任何性能问题,请不要使用someDelegate.DynamicInvoke(...)或someMethod.Invoke(...)。除了Marc的建议之外,您还可以通过指定“优化”编译器选项来提高速度:varres=foo.CompileAssemblyFromSource(newSystem.CodeDom.Compiler.CompilerParameters(){GenerateInMemory=true,CompilerOptions="/optimize"},想想值得展示所有潜在选项的外观及其性能特征。给出以下帮助程序类和函数:publicvoidTest(Funcfunc){varwatch=newStopwatch();观看。开始();for(vari=0;i设置和执行:using(Microsoft.CSharp.CSharpCodeProviderfoo=newMicrosoft.CSharp.CSharpCodeProvider()){varres=foo.CompileAssemblyFromSource(newSystem.CodeDom.Compiler.CompilerParameters(){GenerateInMemory=true},"publicclassFooClass{publicintExecute(){return1;}}");varreal=newFooClass();Test(()=>real.Execute());//基准测试,直接调用vartype=res.CompiledAssembly.GetType("FooClass");varobj=Activator.CreateInstance(type);varmethod=type.GetMethod("Execute");varinput=newobject[]{};Test(()=>(int)method.Invoke(obj,input));//反射调用动态dyn=Activator.CreateInstance(type);Test(()=>dyn.Execute());//动态对象调用varaction=(Func)Delegate.CreateDelegate(typeof(Func),null,method);Test(()=>action());//委托}结果是:8//直接771//反射调用41//dynamicobjectinvoke7//delegate那么在那些你不能使用delegates的情况下(如果你还不够?),你可以试试dynamic以上就是C#学习教程:以原生速度运行动态编译的C#代码。..这个怎么样?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
