Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewBag access performance

In a View that accesses the same value from a ViewBag multiple times, is it better to store this value in a local variable rather than frequently access the ViewBag object?

like image 789
John Smith Avatar asked Apr 20 '26 17:04

John Smith


1 Answers

ViewBag is just a dynamic wrapper around ViewData. So when you write ViewBag.Foo you are basically querying ViewData["Foo"]. But since this is dynamic resolution done at runtime there's obviously a cost to it. This cost is something that you should not be worried about because it is so small that it won't significantly affect the performance of your application and I wouldn't bother caching the result into a local variable.

What I would bother with is the usage of ViewBag that I would most definitely get rid of in favor if view models. So instead of writing @ViewBag.Foo you will have a view model the Foo property and inside your view you will simply be working with it - @Model.Foo. And as you know a calling a property getter will be blazing fast. Not only it will be fast but you will benefit from strong typing and Intellisense in your views.

like image 99
Darin Dimitrov Avatar answered Apr 22 '26 13:04

Darin Dimitrov