Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 高性能`尝试…捕获'(可选?)_C#_Performance_Loops_Try Catch_Gdi+ - Fatal编程技术网

C# 高性能`尝试…捕获'(可选?)

C# 高性能`尝试…捕获'(可选?),c#,performance,loops,try-catch,gdi+,C#,Performance,Loops,Try Catch,Gdi+,这听起来可能是个奇怪的问题,但 我用C#中的GDI+编写了一种图形计算器。我对结果和它“通常”的表现相当满意 唯一的问题是,如果函数没有完全定义⁾, 渲染方法将有巨大的性能问题,这是由于我的渲染循环中的try..catch-块造成的: private void draw(....,Graphics g) { // this is e.g. the function ƒ(x) := x⁻¹ Func<double, double> mathematical_method

这听起来可能是个奇怪的问题,但
我用C#中的GDI+编写了一种图形计算器。我对结果和它“通常”的表现相当满意

唯一的问题是,如果函数没有完全定义⁾, 渲染方法将有巨大的性能问题,这是由于我的渲染循环中的
try..catch
-块造成的:

private void draw(....,Graphics g)
{
    // this is e.g. the function ƒ(x) := x⁻¹
    Func<double, double> mathematical_method = .....;

    ...

    // The variables `left` and `right` are the visible pixels translated
    // into function coordinates, so that we only draw the pixels we really need
    for (double x = left; x < right; x += step)
        try
        {
            // Draws the lines of the graph at their respected points
            g.Draw( ......  x, mathematical_method(x));
        }
        catch
        {
            // in case of a non-definition
            g.Draw( ..whatever.. )
        }

    ...
}
private void draw(..,图形g)
{
//这是例如函数ƒ(x):=x⁻¹
Func数学方法=。。。。。;
...
//变量'left'和'right'是转换后的可见像素
//转换成函数坐标,这样我们就只画出真正需要的像素
用于(双x=左;x<右;x+=步进)
尝试
{
//在图形的相应点绘制线
g、 绘制(……x,数学_方法(x));
}
抓住
{
//在非定义的情况下
g、 画(…随便什么)
}
...
}
正如您可能已经猜到的-这不是最好的解决方案,因此我想知道,是否有可能使此
try..catch
-块更有效(例如,通过某种方式禁用负责堆栈跟踪收集等的CLR方法),或者我如何解决此问题。。。。
编辑№1:我忘了提到,用户可以在计算器中输入任何数学表达式(无需给出表达式的完整定义集)-因此,
if…else
实际上不是一个选项

我的随机想法:我可以以某种方式实现一个
函数缓存
,它在第一次绘图迭代中使用
try..catch
,然后在没有定义函数f的地方“学习”。

1) “未完全定义”指的是功能
ƒ:ℝ\{0}⟶ℝ : x⟼x⁻CharStyle
未为x值定义的
0

绘图的成功/失败可以事先知道吗?如果是这样,考虑使用<代码>如果是其他的/COD>语句,它会加快你的速度。异常处理程序是用来捕捉不可预知的异常的。这是你应该用
if
检查的东西。什么提供了
数学方法
?(顺便说一句,现在是开始遵循.NET命名约定的好时机…)我很惊讶
try/catch
有点贵,但与
Draw
相比应该可以忽略不计。您是否尝试在不附加调试器的情况下以发布模式启动代码?性能问题是否仍然存在?问题在于您的函数似乎正在为“未定义”的情况抛出异常。更好的替代方法是将其定义为
Func
,并在这种情况下返回
null
,因此图形代码可以使用不带
try/catch
的结果。