gpt4 book ai didi

c# - ThreadLocal 性能与使用参数

转载 作者:太空狗 更新时间:2023-10-29 23:17:07 25 4
gpt4 key购买 nike

我目前正在为公式语言实现运行时(即函数集合)。有些公式需要将上下文传递给它们,我创建了一个名为 EvaluationContext 的类,其中包含我需要在运行时访问的所有属性。

使用 ThreadLocal<EvaluationContext>似乎是使此上下文可用于运行时函数的不错选择。另一种选择是将上下文作为参数传递给需要它的函数。

我更喜欢使用 ThreadLocal,但我想知道与通过方法参数传递评估上下文相比是否存在任何性能损失。

最佳答案

我创建了下面的程序,使用参数比使用 ThreadLocal 字段更快。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestThreadLocal
{
internal class Program
{
public class EvaluationContext
{
public int A { get; set; }
public int B { get; set; }
}

public static class FormulasRunTime
{
public static ThreadLocal<EvaluationContext> Context = new ThreadLocal<EvaluationContext>();

public static int SomeFunction()
{
EvaluationContext ctx = Context.Value;
return ctx.A + ctx.B;
}

public static int SomeFunction(EvaluationContext context)
{
return context.A + context.B;
}
}



private static void Main(string[] args)
{

Stopwatch stopwatch = Stopwatch.StartNew();
int N = 10000;
Task<int>[] tasks = new Task<int>[N];
int sum = 0;
for (int i = 0; i < N; i++)
{
int x = i;
tasks[i] = Task.Factory.StartNew(() =>
{
//Console.WriteLine("Starting {0}, thread {1}", x, Thread.CurrentThread.ManagedThreadId);
FormulasRunTime.Context.Value = new EvaluationContext {A = 0, B = x};
return FormulasRunTime.SomeFunction();
});
sum += i;
}
Task.WaitAll(tasks);

Console.WriteLine("Using ThreadLocal: It took {0} millisecs and the sum is {1}", stopwatch.ElapsedMilliseconds, tasks.Sum(t => t.Result));
Console.WriteLine(sum);
stopwatch = Stopwatch.StartNew();

for (int i = 0; i < N; i++)
{
int x = i;
tasks[i] = Task.Factory.StartNew(() =>
{
return FormulasRunTime.SomeFunction(new EvaluationContext { A = 0, B = x });
});

}
Task.WaitAll(tasks);

Console.WriteLine("Using parameter: It took {0} millisecs and the sum is {1}", stopwatch.ElapsedMilliseconds, tasks.Sum(t => t.Result));
Console.ReadKey();
}
}
}

关于c# - ThreadLocal 性能与使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com