Am 11.01.2011 21:28, schrieb Nobody:
It would be interesting to see if there is any overhead that makes it as
slow as the alternatives that you have tried, and compared to the overhead
in calling the DLL function.
I did some performance tests. Before posting the source and the results,
I wanted to make the code look neater. With the "redesigned" version, I
got different results even though it does exactly the same. Although I'm
aware of the side-effects of optimizations, there seem to be several
influences that don't allow me to post robust figures.
Despite, and only for the sake of completeness, I post the source, so you
can play with and modify it and make your own measure experiences. I don't
comment it now.
For my part, these files can be closed now.
Option Infer On
Option Strict On
Imports Microsoft.VisualBasic
Imports System
Imports System.Diagnostics
Imports System.Reflection
Imports System.Reflection.Emit
Friend Class Main
Private Delegate Function ToInt32Delegate(ByVal value As Double) As Integer
Private Shared ReadOnly ConversionDelegate As ToInt32Delegate = CreateConversionDelegate()
Private Shared D As Double = 7.9R
Private Shared i, j As Integer
Shared Sub Main()
Dim duration As TimeSpan
duration = RunTest()
MsgBox(duration.ToString)
duration = RunTest()
MsgBox(duration.ToString)
End Sub
Private Shared Function RunTest() As TimeSpan
Dim watch As Stopwatch
watch = Stopwatch.StartNew
For Project1.Main.i = 1 To 1000000000
' optimized not optimized
'Project1.Main.j = CInt(D) '23.3 16.3
'Project1.Main.j = ConversionDelegate(D) ' 6.9 14.5
'Project1.Main.j = DoubleToIntTableHelper.Main.ToInt32(D) ' 5.6 16.6
'Project1.Main.j = Convert.ToInt32(D) '11.9 22.0
Next
watch.Stop()
Return watch.Elapsed
End Function
Private Shared Function CreateConversionDelegate() As ToInt32Delegate
Dim AssyName As New AssemblyName("ConversionHelper")
Dim AssyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(AssyName, AssemblyBuilderAccess.Run)
Dim ModuleBuilder = AssyBuilder.DefineDynamicModule(AssyName.Name)
Dim TypeBuilder = ModuleBuilder.DefineType("Main", TypeAttributes.Public)
Dim ParameterTypes As Type() = {GetType(Double)}
Dim MethodBuilder = TypeBuilder.DefineMethod( _
"ToInt32", MethodAttributes.Static Or MethodAttributes.Public, GetType(Int32), ParameterTypes)
Dim Generator As ILGenerator = MethodBuilder.GetILGenerator()
Dim t As Type
Generator.Emit(OpCodes.Ldarg_0)
Generator.Emit(OpCodes.Conv_I4)
Generator.Emit(OpCodes.Ret)
t = TypeBuilder.CreateType()
Return DirectCast( _
[Delegate].CreateDelegate(GetType(ToInt32Delegate), t, MethodBuilder.Name), _
ToInt32Delegate _
)
End Function
End Class