When we want to raise an error in the program, we usually use throw new exception and put the appropriate text of the error in the exception class. But if the number of these export errors increases, it will increase the assembly code. When throwing is used in one method, several lines are created to export the error, and if we use this code in the methods, the number of generated assembly lines increases. Consider the following code, for example:

public static int ThrowExceptionDirectly()
{
    if (_number <= 0)
    {
        throw new Exception("Number should be greater than zero");
    }

    return ++_number;
}

The generated assembly code for the error code snippet is as follows:

            {
 nop  
                throw new Exception("Number should be greather than zero");
 mov         rcx,7FFF0C329410h  
 call        00007FFF6BE0AF00  
 mov         qword ptr [rbp+28h],rax  
 mov         ecx,1  
 mov         rdx,7FFF0C342820h  
 call        00007FFF6BDA49D0  
 mov         qword ptr [rbp+20h],rax  
 mov         rdx,qword ptr [rbp+20h]  
 mov         rcx,qword ptr [rbp+28h]  
 call        00007FFF0C295EA0  
 mov         rcx,qword ptr [rbp+28h]  
 call        00007FFF6BDAC9F0  
            }

But if we use a Helper to raise errors, the generated assembly code will be less. for example:

public static int ThrowExceptionWithThrowHelper()
{
    if (_number <= 0)
    {
        ThrowHelper.ThrowException("Number should be greater than zero");
    }
    return ++_number;
}

The assembly code for the above code snippet is as follows:

            {
 nop  
                ThrowHelper.ThrowException("Number should be greather than zero");
 mov         rcx,1B81A1C3080h  
 mov         rcx,qword ptr [rcx]  
 call        00007FFF0C2A5AB0  
 nop  
            }

As you can see, the assembly code generated in the second method, which used a Helper to export the error, has been reduced. In this case, we have put the code needed to export the error in another method that we can use in different places of the code, and instead of using throw new exception inside the methods and generating more assembly code, use ThrowHelper And generate less code.

ThrowHelper class:

public static class ThrowHelper
{
    public static void ThrowException(string message)
    {
        throw new Exception(message);
    }
}

Sources used:

To view the generated assembly code, you can press Ctrl + Alt + D in Visual Studio while viewing the debug and reach the desired line and view the generated code.

;)

Powered by Froala Editor

Comments