C# Dynamic code and performance considerations

JCOBridge guarantees to the .NET developer a simple and direct way to write code running within JVM. From .NET, using the Dynamic Language Runtime feature, it is possible to write code like you are writing a Java code. The subsystem translates all requests into JVM context, executes it within the JVM and returns back the result.

The use of dynamic code in C# simplify the coding and results in “writing Java code in C# files”. Look at the snippet below:

double a = 2; 
double b = 3; 
double c = Math.PI/2;

/*Dynamic code*/
JVM.ImportPackage("JavaClass");
var javaClass = DynJVM.JavaClass.@new();
var result = javaClass.add(a, b); 
var sin = javaClass.sin(c); 

With the dynamic access you doesn’t need to call the Invoke methods to execute java code, you can simply call the methods. The snippet below shows how to do the same using the direct interfaces.

double a = 2; 
double b = 3; 
double c = Math.PI/2;

/*Not Dynamic code*/ 
JVM.ImportPackage("JavaClass");
IJavaObject javaClass = JVM.New("JavaClass") as IJavaObject; 
double result = (double)javaClass.Invoke("add", a, b); 
double sin = (double)javaClass.Invoke("sin", c);

From the point of view of the results both code snippets are equivalent.

Performance

The dynamic code is more clear and easy to use, but this come at a price. The dynamic object shall figure out what to do with syntax after every dot, and need to understand what to do with this. This internal search for the meaning of the syntax consumes resources.

The “Not dynamic code” is more complex to write, is less intuitive, but in situations similar to the above example the performance comparison figure out not dynamic code is 250x time faster.

The performance gain can be simply ignored if you need to call few objects/methods but can result in poor performances if you need to do thousands of calls.