Interop function call from Excel to PowerPoint much slower in C# compared to VB.net (when run for the first time)

56 Views Asked by At

I have a VSTO Excel addin as well as a VSTO PowerPoint addin. I am calling one of the PowerPoint addin functions from my Excel addin with the below code:

 Application pptApp = null;
 try
 {
     pptApp = (Application)Marshal.GetActiveObject("Powerpoint.Application");
 }
 catch (Exception)
 {
     return;
 }

if(pptApp is null) return;
     
var addIn = pptApp.COMAddIns.Item(ref argIndex);

if (addIn.Connect)
{
    ((dynamic)addIn.Object).ExternalFunctionCall(); // this is the slow function call
}

This works as expected but the first time I call this function it takes several seconds to execute. On further calls there is no delay. If I convert the above code to VB.net and run it, there is no such initial delay.

The delay occurs in Debug as well as in release mode.

Any idea why that is and how can I fix this?

1

There are 1 best solutions below

2
Eugene Astafiev On

Only (MS)IL can shed the light on why you are getting different results with C# and VB.NET. You need to compare the results produced by the C# and VB.NET compilers.

Managed code is written in one of the high-level languages that can be run on top of .NET, such as C#, Visual Basic, F# and others. When you compile code written in those languages with their respective compiler, you don't get machine code. You get Intermediate Language code which the runtime then compiles and executes. C++ is the one exception to this rule, as it can also produce native, unmanaged binaries that run on Windows.

What is "Intermediate Language" (or IL for short)? It is a product of compilation of code written in high-level .NET languages. Once you compile your code written in one of these languages, you will get a binary that is made out of IL. It is important to note that the IL is independent from any specific language that runs on top of the runtime; there is even a separate specification for it that you can read if you're so inclined.

Once you produce IL from your high-level code, you will most likely want to run it. This is where the CLR takes over and starts the process of Just-In-Time compiling, or JIT-ing your code from IL to machine code that can actually be run on a CPU. In this way, the CLR knows exactly what your code is doing and can effectively manage it.

Intermediate Language is sometimes also called Common Intermediate Language (CIL) or Microsoft Intermediate Language (MSIL).