A question regarding re-using objects vs creating/destroying after each use.

TNode 20 Reputation points
2025-05-05T17:06:29.0866667+00:00

Consider this pseudo code:

I would assume the first version is better since you only create the object once BUT one is also constantly overwriting the DateOnly value. So, which would be better?

DateObject dateObject = new DateObject();

for (int i = 1; i < lines.Length; i++)
{	
	dateObject.DateOnly = <some value>
}

VS

for (int i = 1; i < lines.Length; i++)
{
	DateObject dateObject = new DateObject();

	dateObject.DateOnly = <some value>
}

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,454 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 75,386 Reputation points Moderator
    2025-05-05T18:20:15.2+00:00

    it depends on the use case. as the object is not defined, we do not know the side effects of reading and writing a property.

    in your sample, you a setting a value type, which requires no allocation other than the object (unless there are side effects). so pre-allocating the object requires only one memory allocation, vs one per loop. in the sample code the object is only used in the loop and is not used outside, so its all local.

    a localized version one might be:

    // local scope dateObject, so it unavailable outside the loop
    { 
       DateObject dateObject = new DateObject();
       for (int i = 1; i < lines.Length; i++)
       {	
    	   dateObject.DateOnly = <some value>
       }
    }
    

    this limits the dateObject property changes to the loop. but if the loop is only accessing a couple properties of an object, maybe it should access a copy of the properties, or not use the object at all.

    DateObject dateObject = new DateObject();
    
    ...
    
    // local scope with guard
    if (dateObject != null)
    { 
       // anonymous object with copy of property values
       var temp = new { DateOnly, OtherProp};
       for (int i = 1; i < lines.Length; i++)
       {	
    	   temp.DateOnly = <some value>;
       }
    }
    

    again a DateTime is a value type the follow works with no allocations:

    DateObject dateObject = new DateObject();
    
    ...
    
    for (int i = 1; i < lines.Length; i++)
    {	
       var temp = dateObject.DateOnly;
       temp = <some value>;
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.