Share via


Performance enhancements (TryParse, LCG, StopWatch) sample code

using System;

using System.Collections.Generic;

using System.Text;

using System.Windows.Forms; // msgbox

using System.Diagnostics; // Stopwatch

using System.Reflection; // LCG (Light Weight CodeGen)

using System.Reflection.Emit; // LCG (Light Weight CodeGen)

namespace Perf

{

    class Program

    {

        static void Main(string[] args)

        {

            // Try-Parse

            // @"^-?\d+$" Int, Smallint, TinyInt

            TryandParse("ABC");

            TryandParse("123");

            TryandParse("123.12");

            // StopWatch

            Stopwatch stopWatch;

            TimeSpan ts;

            stopWatch = new Stopwatch();

            String stringTimeFormat = "00:00:00.00";

           stopWatch.Start();

            ShowLCG();

            stopWatch.Stop();

            ts = stopWatch.Elapsed;

            stringTimeFormat = String.Format("{0:00}:{1:00}:{2:00}:{3:00}",

                ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10);

            MessageBox.Show("Formated Elapsed Time\n" + stringTimeFormat + "\nElapsed milliseconds\n" + ts.Milliseconds, "StopWatch");

        } // void Main

        public static void TryandParse(string stringIn)

        {

            /*

             * Throwing exceptions can negatively impact performance.

                try

                     {

                           Convert.ToInt32(stringIn);

                     }

                     catch (Exception e)

                     {

                           throw new ShuttleException(@"Invalid Int32, " + e.Message);

                     }

           * For code that routinely fails, you can use design patterns to minimize performance issues.

            */

            bool DoesConvert = false;

            int intValue = 0;

            try

            {

                DoesConvert = Int32.TryParse(stringIn, out intValue); // does not throw

                if (DoesConvert)

                    Trace.WriteLine(stringIn + ", String does convert to Int32");

                else

                    Trace.WriteLine(stringIn + ", String does NOT convert to Int32");

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

            }

        } // TryandParse

        public static void ShowLCG() // Lightweight Code Gen

        {

            /* DynamicMethod class is new in the .NET Framework version 2.0.

                Use the DynamicMethod class to generate and execute a method at run time

                without having to generate a dynamic assembly (AssemblyBuilder)

                and a dynamic type (DefineDynamicModule, DefineType)to contain the method.

                Dynamic methods are the most efficient way to generate and execute small amounts of code.

            */

            DynamicMethod dynamicMethod = new DynamicMethod("HelloISV" // Method name HelloISV

                , typeof(void) // method void return type

                , new Type[] { } // method parms

                , typeof(Program) // Create the method in the class Program

                , false);

            // Get an ILGenerator and emit a body for the dynamic method,

            // using a stream size larger than the IL that will be

            // emitted.

            ILGenerator iLGenerator = dynamicMethod.GetILGenerator(256);

            // Load the first parameter, which is a string, onto the stack

            iLGenerator.Emit(OpCodes.Ldstr, "Hello! ISV/VAR/SI");

            // Call the Console.Writeline

            iLGenerator.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));

            iLGenerator.Emit(OpCodes.Ret); // returns from the current method

            //Set next statement

            //Console.WriteLine("ENC"); // Check Tools options, Debugging, ENC enabled.

            dynamicMethod.Invoke(null, null); // Break point here

        } // void ShowLCG()

    } // class Program

} // namespace Perf

Comments