IntPtr cast vs new

I just looked at an example, and in it I saw the code

return new IntPtr(handle);

After we looped through our code, I found that we already used a similar pattern, but in our code we had almost the same thing:

return (IntPtr)handle;

Is there a difference between the two? Will the second one be β€œbetter” in any way, since it does not allocate new memory, or is it a listing just hiding the same constructor under it?

+3
source share
4 answers

In your examples, I assume the descriptor is an integer value? IntPtr declares an explicit conversion from Int32 (int) and Int64 (long), which simply calls the same constructor:

public static explicit operator IntPtr(int value)
{
    return new IntPtr(value);
}

, , .

+8

Reflector , :

[Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)]
public struct IntPtr : ISerializable
{
    ...

    [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
    public static explicit operator IntPtr(int value)
    {
        return new IntPtr(value);
    }

}
+5

IntPtr - , new .

, - , . , - JIT, , , ( , , ).

, , , .

+2

, - , . , Visual Studio 2010

, 10 10 , Release ( , ):

() : ~ 32 : ~ 26

(Release) : ~ 20 : ~ 22

++ gcnew, .

. : "IntPtr ^ ptr = (IntPtr) i;" vs : "IntPtr ^ ptr = (IntPtr) i;".

() : ~ 91 : ~ 127

(Release) : ~ 22 : ~ 124

, , , # , ++, - . IntPtr , . , : "IntPtr ptr = (IntPtr) i;". ~ 24 ( ) (~ 22 ). , , 22 , 90 .

#, , . , Release , ~ 22 . #, , VS 2010 . , Managed ++/CLI, , . gcnew , 6 ... ++/CLI, . (#): ( ++ , , Average() , ).

    static void Main()
    {
        List<int> castTimings = new List<int>();
        List<int> allocTimings = new List<int>();

        for (int i = 0; i < TEST_RUNS; ++i)
        {
            castTimings.Add(RunCastMethod().Milliseconds);
            allocTimings.Add(RunAllocationMethod().Milliseconds);
        }

        MessageBox.Show(string.Format("Casting Method took: {0}ms", castTimings.Average() ));
        MessageBox.Show(string.Format("Allocation Method took: {0}ms", allocTimings.Average() ));
    }

    private static TimeSpan RunAllocationMethod() {
        DateTime start = DateTime.Now;

        for (int i = 0; i < TEST_ITERATIONS; ++i)
        {
            IntPtr ptr = new IntPtr(i);
        }

        return ( DateTime.Now - start );
    }

    private static TimeSpan RunCastMethod()
    {
        DateTime start = DateTime.Now;

        for (int i = 0; i < TEST_ITERATIONS; ++i)
        {
            IntPtr ptr = (IntPtr) i;
        }

        return (DateTime.Now - start);
    }
+2
source

Source: https://habr.com/ru/post/1714466/


All Articles