CSharpCodeProvider编译性能

时间:2008-08-07 12:01:15

标签: c# performance compiler-construction

CompileAssemblyFromDom CompileAssemblyFromSource 更快?

,因为它可能会绕过编译器前端。

2 个答案:

答案 0 :(得分:7)

CompileAssemblyFromDom编译为.cs文件,然后通过普通的C#编译器运行。

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;

namespace CodeDomQuestion
{
    class Program
    {

        private static void Main(string[] args)
        {
            Program p = new Program();
            p.dotest("C:\\fs.exe");
        }

        public void dotest(string outputname)
        {
            CSharpCodeProvider cscProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.MainClass = null;
            cp.GenerateExecutable = true;
            cp.OutputAssembly = outputname;

            CodeNamespace ns = new CodeNamespace("StackOverflowd");

            CodeTypeDeclaration type = new CodeTypeDeclaration();
            type.IsClass = true;
            type.Name = "MainClass";
            type.TypeAttributes = TypeAttributes.Public;

            ns.Types.Add(type);

            CodeMemberMethod cmm = new CodeMemberMethod();
            cmm.Attributes = MemberAttributes.Static;
            cmm.Name = "Main";
            cmm.Statements.Add(new CodeSnippetExpression("System.Console.WriteLine('f'zxcvv)"));
            type.Members.Add(cmm);

            CodeCompileUnit ccu = new CodeCompileUnit();
            ccu.Namespaces.Add(ns);

            CompilerResults results = cscProvider.CompileAssemblyFromDom(cp, ccu);

            foreach (CompilerError err in results.Errors)
                Console.WriteLine(err.ErrorText + " - " + err.FileName + ":" + err.Line);

            Console.WriteLine();
        }
    }
}

显示(现在不存在)临时文件中的错误:

  

)预期 - c:\ Documents and Settings \ jacob \ Local Settings \ Temp \ x59n9yb-.0.cs:17

     

预期 - c:\ Documents and Settings \ jacob \ Local Settings \ Temp \ x59n9yb-.0.cs:17

     

无效的表达式术语')' - c:\ Documents and Settings \ jacob \ Local Settings \ Tem p \ x59n9yb-.0.cs:17

所以我猜答案是“不”

答案 1 :(得分:0)

我之前尝试过找到最终的编译器调用,但我放弃了。我有耐心,有很多层接口和虚拟课程。

我认为编译器的源代码阅读器部分不会以DOM树结束,但直觉上我会同意你的观点。将DOM转换为IL所需的工作应该远远少于读取C#源代码。