Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance concerns of instantiating a class multiple times

I'm wondering the performance differences between instantiating a class once in a form or whenever it is needed. For example, say I have a customer form to edit a customer. On the form load, I instantiate a customer class and call a function to return the customer data to populate the form controls.

CustomerInfo customer = new CustomerInfo();
CustomerDetail  cust = customer.GetCustomer(customerId);
txtName. cust.Name;
...

Also on the form there is a save button. When that button is clicked, I create another instance of the Customer class to update the data.

CustomerDetail cust = new CustomerData();
cust.Id = customerId;
cust.Name = txtName.Text;

CustomerInfo customer = new CustomerInfo();
customer.Update(cust);

I know this works fine. However, is it better, performance wise, just to create a single instance of the Customer class for the whole form to call both GetCustomer and Update? I know the GC will take care of those instances, but I'm not sure it would destroy the first instance before going on to the next.

Also, this example I use just two function calls to customer class, but, really, there could be more.

Thanks for the help.

like image 863
Aaron Sanders Avatar asked Dec 22 '22 11:12

Aaron Sanders


1 Answers

The idea should be that you create an instance of Customer for every distinct customer that you are manipulating. So if your form only deals with a single customer then you should have only one instance, but if your form deals with multiple customers then you will have multiple instances.

In terms of performance, that only becomes an issue if you are dealing with many instances, I would say thousands.

like image 82
Vincent Ramdhanie Avatar answered Mar 05 '23 00:03

Vincent Ramdhanie