Home » excel » c# – Why is my XLL slower than my UDF?

c# – Why is my XLL slower than my UDF?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have been trying to speed up a macro by using XLLs, however, it seems is a lot faster with the UDF than with the XLL.

Some data with code profiling demonstrates it

XLL Time for the sub
Proc:module 1 iteration 11.64831 seconds

UDF Time for the sub
Proc:module 1 iteration 4.25986 seconds

It happens on two UDFs that I have converted, factor is abour 2x or 3x slower.
For instance, the XLL function for this is:

[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());

}

The UDF Function is

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

Both were tested for Range(A1:A701) with data and blanks between cells, both work as expected, just XLL is slower.

How to&Answers:
  1. VBA accesses cell contents directly. It uses its native types and 99% of the time a well coded UDF will be faster than an external library doing the same thing.

  2. In your example you are doing doing a lot more in the C# version.

  3. If you really want to improve the performance and take advantage of C# ability to do stuff without looping* 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.