c# 4.0 - What is the practical difference between dynamic and T in C# -
c# 4.0 - What is the practical difference between dynamic and T in C# -
i read type dynamic
in c# 2010. (the corresponding msdn entry)
i confused practical difference between t
, dynamic
while developing generic functions. current tests didn't show new ways utilize dynamic
a way, isn't possible t
. in add-on seems, dynamic needs much more time in runtime accomplish same tasks.
some illustration code create point clear:
// sample object public class sampleobj { public string test { get; set; } }
my test-method (measuring speed well):
static void main(string[] args) { var sampleobj1 = new sampleobj { test = "test1" }; var sampleobj2 = new sampleobj { test = "test2" }; stopwatch c1 = stopwatch.startnew(); bool res1 = compareobjectst<sampleobj>(sampleobj1, sampleobj2); c1.stop(); console.writeline("comparison t: {0} time: {1} ms", res1, c1.elapsedmilliseconds); stopwatch c2 = stopwatch.startnew(); bool res2 = compareobjectsdyna(sampleobj1, sampleobj2); console.writeline("comparison dynamic: {0} time: {1} ms", res2, c2.elapsedmilliseconds); c2.stop(); var instance = new x<sampleobj>(); console.readline(); }
the result is:
comparison t: false time: 6 ms comparing dynamic: false time: 3969 ms
the dynamic functions needs much more time, compared t comparison.
decompiling test application reveals heavy usage of reflection may lead huge amount of time:
private static bool compareobjectsdyna([dynamic] object source1, [dynamic] object source2) { if (<compareobjectsdyna>o__sitecontainer2.<>p__site3 == null) { <compareobjectsdyna>o__sitecontainer2.<>p__site3 = callsite<func<callsite, object, bool>>.create(binder.convert(csharpbinderflags.none, typeof(bool), typeof(program))); } if (<compareobjectsdyna>o__sitecontainer2.<>p__site4 == null) { <compareobjectsdyna>o__sitecontainer2.<>p__site4 = callsite<func<callsite, type, object, object, object>>.create(binder.invokemember(csharpbinderflags.none, "equals", null, typeof(program), new csharpargumentinfo[] { csharpargumentinfo.create(csharpargumentinfoflags.isstatictype | csharpargumentinfoflags.usecompiletimetype, null), csharpargumentinfo.create(csharpargumentinfoflags.none, null), csharpargumentinfo.create(csharpargumentinfoflags.none, null) })); } homecoming <compareobjectsdyna>o__sitecontainer2.<>p__site3.target(<compareobjectsdyna>o__sitecontainer2.<>p__site3, <compareobjectsdyna>o__sitecontainer2.<>p__site4.target(<compareobjectsdyna>o__sitecontainer2.<>p__site4, typeof(object), source1, source2)); }
i considered this post hasn't ansered question.
can tell me, in scenario dynamic much more effective t? (hopefully little practical sample)
short reply generic type t must known @ compile time, dynamic inferred @ runtime.
c#-4.0 generics dynamic
Comments
Post a Comment