-

   rss_rss_hh_new

 - e-mail

 

 -

 LiveInternet.ru:
: 17.03.2011
:
:
: 51

:


[ ] generic-

, 07 2017 . 18:16 +

null. - , , -:


        public void ThrowIfNull(object obj)
        {
            if(obj == null)
            {
                throw new ArgumentNullException();
            }
        }

, object , generic-. generic .


object . (value types) null(Nullable ). , ThrowIfNull(5), , , object, . , , . , , generic , (constraints). Nullable , , nullable , struct.


, BenchmarkDotNet. , , .


public class ObjectArgVsGenericArg
    {
        public string str = "some string";
        public Nullable num = 5;

        [MethodImpl(MethodImplOptions.NoInlining)]
        public void ThrowIfNullGenericArg(T arg)
            where T : class
        {
            if (arg == null)
            {
                throw new ArgumentNullException();
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public void ThrowIfNullGenericArg(Nullable arg)
            where T : struct
        {
            if(arg == null)
            {
                throw new ArgumentNullException();
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        public void ThrowIfNullObjectArg(object arg)
        {
            if(arg == null)
            {
                throw new ArgumentNullException();
            }
        }

        [Benchmark]
        public void CallMethodWithObjArgString()
        {
            ThrowIfNullObjectArg(str);
        }

        [Benchmark]
        public void CallMethodWithObjArgNullableInt()
        {
            ThrowIfNullObjectArg(num);
        }

        [Benchmark]
        public void CallMethodWithGenericArgString()
        {
            ThrowIfNullGenericArg(str);
        }

        [Benchmark]
        public void CallMethodWithGenericArgNullableInt()
        {
            ThrowIfNullGenericArg(num);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run();
        }
    }

Method Mean Error StdDev
CallMethodWithObjArgString 1.784 ns 0.0166 ns 0.0138 ns
CallMethodWithObjArgNullableInt 124.335 ns 0.2480 ns 0.2320 ns
CallMethodWithGenericArgString 1.746 ns 0.0290 ns 0.0271 ns
CallMethodWithGenericArgNullableInt 2.158 ns 0.0089 ns 0.0083 ns

generic nullable 2000 ! - (boxing). CallMethodWithObjArgNullableInt, nullable-int "" . , . generic .


, generic object :


  1. ,

Upd. zelyony . , MethodImpl(MethodImplOptions.NoInlining).

Original source: habrahabr.ru (comments, light).

https://habrahabr.ru/post/332640/

:  

: [1] []
 

:
: 

: ( )

:

  URL