I know that ViewData and ViewBag both use the same backing data and that neither are as good as using strongly typed models in most cases. However when choosing between the two is the dynamic nature of ViewBag slower than using ViewData?
Asp.net-mvc – ViewBag vs ViewData performance difference in MVC
asp.net-mvcasp.net-mvc-3performanceviewbagviewdata
Related Topic
- Javascript – the difference between call and apply
- .net – What’s the difference between ViewData and ViewBag
- C# – File Upload ASP.NET MVC 3.0
- C++ – Why does changing 0.1f to 0 slow down performance by 10x
- Swift Beta performance: sorting arrays
- C# – System.Windows.Application.GetResourceStream returns null
- Python: Referencing another project
Best Answer
Okay - my initial answer basically said 'no' - time for a bit of a u-turn.
It should be 'no' in a perfect dynamic world - but upon closer inspection it would appear that there will either be no difference (accounting for JIT magic) or it might be ever-so-slightly slower, although not enough to warrant not using it (I certainly am).
In theory if properly implemented, the ViewBag would ultimately outperform the use of the ViewData dictionary because the binding of the expressions (e.g.
ViewBag.Foo
) is very well cached across the different CallSites that the compiler will generate (reflect a method that does a read or write to theViewBag
and you'll see what I mean).The caching layers of the DLR are well documented (if a little difficult to understand once you get in depth) but basically the runtime does its best to 'remember' where a given value instance is once its bound it - for example via a Set or Get statement.
BUT The caching, its use and effectiveness, is entirely dependent upon the underlying implementations of classes/interfaces such as DynamicObject, IDynamicMetaObjectProvider etc; as well as the end-result of the Get/Set expression binding.
In the case of the MVC internal DynamicViewDataDictionary class - it ultimately ends up binding to this:
For
var a = ViewBag.Foo
And
For
ViewBag.Foo = Bar;
In other words - the statements are effectively being rewritten to wrappers around the dictionary indexer.
Because of that, there's certainly no way it could be faster than doing it yourself.
Were
ViewData
to feed off ofViewBag
, instead of the other way around, and hadViewBag
then been implemented with even something likeExpandoObject
, then it might be a different story - as the dynamic implementation ofExpandoObject
is much more intelligent and the caching rules it employs allow for some pretty cool runtime optimisations.In Conclusion
(thanks to Shawn McLean for suggesting one was needed!)
ViewBag will be slower than ViewData; but probably not enough to warrant concern.