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

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,187 questions
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.
10,275 questions
0 comments No comments
{count} votes

7 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    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