TransWikia.com

memory difference between c# new class instance vs calling method

Stack Overflow Asked by Dan Pettis on December 27, 2021

I am building a logging system within my c# application. Currently I have a logging method that I call which writes to log file. e.g.

Log("Hello World");

What I would like to do is write a class instead that I instantiate each time I want to Log something, and the constructor writes to the log file. e.g.

new WriteLog {Message="Hello World"};

The reason for this is more flexibility with parameters.

However I want to know if instantiating a class every time I log something has more memory cost than calling the method. Does every class that I instantiate persist in memory?

2 Answers

You can create an Extension of the Logger class and you can use logger in the project to log exception or information.

Sample Code

public static class LoggerExtensions
{
    public static void LogCustomError(this ILogger logger, string message, params object[] args) => logger.LogError(message, args);
    public static void LogCustomError(this ILogger logger, Exception exception, string message, params object[] args) => logger.LogException(exception, message, args);

}

Use

public class TestClass : ITestClass
{
private readonly ILogger<ITestClass> _logger;

public TestClass(ILogger<TestClass> logger)
{
    _logger = logger;
}

public voidTesMethod()
{
    try
    {

    }
    catch (Exception ex)
    {
        _logger.LogException(ex, "Got error");
    }
}

}

Answered by Ranjeet Kumar on December 27, 2021

Temporarily they will persist but they will be removed in time by the garbage collector. Anyway unless you make extremely many calls in short time this shouldnt make any larger impact on memory.

I do however question if this is a good usage of a class. You are missusing a constructor as I see it and I dont think it will work with your code. A constructor should initiate data, not do actions such as log data. Also in your example the constructor is called before you assign the properties.

I think the real problem is why you feel a class has more flexibility in parameters.

Could it be you have not tried named arguments and optional arguments. That might be something you might want to look up.

Answered by Achtung on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP