creating new objects in a static method

simplify3000 1 Reputation point
2022-09-16T16:30:19.45+00:00

Hi all,

I have a static method as follows:

public static class Helper  
{  
public static void WriteMessage (string message)  
{  
   ///////////////  
   var myObj = new MyObjectDetail();  
   ///////////////  
   myObj.message = message;  
   myObj.TimeStamp = DateTime.UtcNow();  
   Console.WriteLine(myObj.ToJsonFormat());  
}  
}  

this will be called frequently as:
Helper.WriteMessage("method A started"); //etc.

My question is,
By creating a new object inside every call to the static "WriteMessage" (var myObj = new MyObjectDetail(); )

  1. does that have a performance impact?
  2. is there a possibility of data used incorrectly between threads or calls, e.g. call1 writing out a message meant for call2?

Thanks

Developer technologies ASP.NET ASP.NET Core
Developer technologies C#
0 comments No comments
{count} votes

7 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-09-19T15:40:38.957+00:00

    Your analysis is wrong, while creating objects costs more than not creating objects, it is pretty cheap (depending on the object). in your code the ToJsonFormat() call is the big expense. For performance, using a JsonWriter would be a better improvement.

    creating objects in static methods is no different than in instance methods. the main difference is a static method is called directly rather than thru an instance vtable. static methods are just as thread safe as instance methods.

    note: do not confuse static methods (all methods are really static, instance methods just get passed the this pointer) with static variables, which generally are not thread safe.

    0 comments No comments

  2. simplify3000 1 Reputation point
    2022-09-21T21:58:22.513+00:00

    ok thank you for the info, appreciate everyone's replies here.

    0 comments No comments

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.