IronRuby使用变量时的性能问题 [英] IronRuby performance issue while using Variables

查看:85
本文介绍了IronRuby使用变量时的性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用IronRuby的非常简单的表达式求值器的代码

Here is code of very simple expression evaluator using IronRuby

public class BasicRubyExpressionEvaluator
{
    ScriptEngine engine;
    ScriptScope scope;
    public Exception LastException
    {
        get; set;
    }
    private static readonly Dictionary<string, ScriptSource> parserCache = new Dictionary<string, ScriptSource>();
    public BasicRubyExpressionEvaluator()
    {
        engine = Ruby.CreateEngine();
        scope = engine.CreateScope();

    }

    public object Evaluate(string expression, DataRow context)
    {
        ScriptSource source;
        parserCache.TryGetValue(expression, out source);
        if (source == null)
        {
            source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.SingleStatement);
            parserCache.Add(expression, source);
        }

        var result = source.Execute(scope);
        return result;
    }
    public void SetVariable(string variableName, object value)
    {
        scope.SetVariable(variableName, value);
    }
}

这是问题.

var evaluator = new BasicRubyExpressionEvaluator();
evaluator.SetVariable("a", 10);
evaluator.SetVariable("b", 1 );
evaluator.Evaluate("a+b+2", null);

var evaluator = new BasicRubyExpressionEvaluator();
evaluator.Evaluate("10+1+2", null);

第一个速度比第二个速度慢 25倍.有什么建议? String.Replace不是我的解决方案.

First Is 25 times slower than second. Any suggestions? String.Replace is not a solution for me.

推荐答案

我不认为您看到的性能是由于变量设置引起的;无论您在做什么,程序中IronRuby的第一次执行总是比第二次执行慢,因为大多数编译器直到实际运行代码时才加载(出于启动性能的原因).请再次尝试该示例,也许可以循环运行每个版本的代码,您会发现性能大致相当;变量版本确实有一些方法派遣来获取变量的开销,但是如果您足够运行它应该可以忽略不计.

I do not think the performance you are seeing is due to variable setting; the first execution of IronRuby in a program is always going to be slower than the second, regardless of what you're doing, since most of the compiler isn't loaded in until code is actually run (for startup performance reasons). Please try that example again, maybe running each version of your code in a loop, and you'll see the performance is roughly equivalent; the variable-version does have some overhead of method-dispatch to get the variables, but that should be negligible if you run it enough.

此外,在您的托管代码中,您如何在字典中使用ScriptScopes?我会改用CompiledCode(engine.CreateScriptSourceFromString(...).Compile()的结果),因为这将有助于重复运行.

Also, in your hosting code, how come you are holding onto ScriptScopes in a dictionary? I would hold onto CompiledCode (result of engine.CreateScriptSourceFromString(...).Compile()) instead -- as that will help a lot more in repeat runs.

这篇关于IronRuby使用变量时的性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆