More performative way to return data to the View

Asked

Viewed 252 times

3

In a view where we return a list of objects, and we need to demonstrate the quantity, as a small report, using some conditions.

What is the most performative way to return data to view?

Explaining better.

When we return a list of objects to view, for example:

Using the example from Microsoft, we have:

public class Movie 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
    public DateTime ReleaseDate { get; set; } 
    public string Genre { get; set; } 
    public decimal Price { get; set; } 
} 

And return all the Movies registered in our controller, for example:

public ActionResult Index() 
        { 
            return View(db.Movies.ToList()); 
        } 

In this case, say we want to know the amount of movies and show on a table, we could bring in a ViewBag thus:

  public ActionResult Index() 
        { 
            var filmes = db.Movies.ToList();
            ViewBag.TotoalFilmes = filmes.Count();
            return View(filmes); 
        }  

And in the view just show the ViewBag, thus:

<p> Total: @ViewBag.TotalFilmes</p>

This is one way of doing it, but another would simply be using the Count() directly on view, thus:

<p> Total: @Model.Count</p>

That’s where my question comes from: Which of the two forms is "better" (more performative)?

Remembering, that in the example I just showed with A ViewBag. But I would like to know if we have several data.

If you have a third way that’s better, I’ll be happy to meet you too.

1 answer

1


Essentially, it makes no difference. It can, and I said only that there may be a small difference between one or the other, but it will be irrelevant, especially near the whole that will be executed.

It will be difficult to measure reliably and only measurements can tell you which is faster indeed. I don’t think it will make any difference. Certainly nothing that’s noticeable.

If you are having performance problems it will not be because of this, if you are not having problems it is a micro optimization useless. Do what makes more sense to the code, which is more readable to you, which is better maintainability.

In some situation, where the code is, it may be relevant, but not in this or most of them. Even this relevance is not so strong. And if it’s important, you probably have some major code problem.

I have my doubts whether it would work exactly as you put it, but this is not relevant to the question.

  • I’m not facing any problems. Because I see in articles and in codes here in the company of the two forms (well, at least here it worked, kkkkkkkk). Hence I came to this doubt. If there is no "significant" difference, I will do as you mentioned, see where it looks best for the code. Thanks for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.