为什么我的 XLL 比我的 UDF 慢?

Why is my XLL slower than my UDF?

我一直在尝试使用 XLL 来加速宏,但是,UDF 似乎比 XLL 快得多。

一些带有代码分析的数据证明了这一点

XLL时间为子 Proc:module 1 次迭代 11.64831 秒

UDF时间为子 Proc:module 1 次迭代 4.25986 秒

它发生在我转换的两个 UDF 上,因子大约慢 2 倍或 3 倍。 例如,XLL 函数为:

[ExcelFunction(Description="Joins cell values", Category="Example1")]
public static object RangeJoin(object[,] cells)
{
List<string> list = new List<string>();
foreach (object o in cells){      
if ( !(o is ExcelEmpty) )
list.Add(o.ToString()); }
return string.Join(" ", list.ToArray());

}

UDF函数是

Function RangeJoin(Rng As Range) As String
Dim vArr As Variant
Dim v As Variant
vArr = Rng

RangeJoin = vbNullString

For Each v In vArr
  RangeJoin = RangeJoin & " " & v
 Next v

End Function

两者都针对范围 (A1:A701) 进行了测试,单元格之间有数据和空白,两者都按预期工作,只是 XLL 较慢。

  1. VBA 直接访问单元格内容。它使用其本机类型,并且 99% 的情况下,编码良好的 UDF 将比执行相同操作的外部库更快。

  2. 在您的示例中,您在 C# 版本中做了很多事情。

  3. 如果你真的想提高性能并利用 C# 的能力来做一些事情而无需循环* you should consider passing a Range object to your external library pretending like you're actually passing a 1D array. Receive that in C# and you're good to go for all the cool stuff like LINQ