2

In the example below, will a new StringBuilder(255) be created every time the static Flog.Log() function is called, or will it only be created the first time the method is called?

public class Flog {

    public static void Log(FlogType flogType, string msg, params System.Object[] p) {

        StringBuilder sb = new StringBuilder(255);
        sb.Length = 0;
        sb.AppendFormat(msg, p);
        Log(flogType, sb.ToString());
    }
}

I realise I could work around this with a static member variable.

Edit: The purpose of the question is one of optimisation - in some languages initialisation of the StringBuilder sb variable will only occur once.

Matt Parkins
  • 24,208
  • 8
  • 50
  • 59
  • everytime, since the method is static, not the variables, and they will run out of scope and be flagged for garbage collection – Noctis Sep 17 '16 at 10:55
  • I don't think this deserves to be closed, as this question relates more to compiler optimization IMO. – EvilTak Sep 17 '16 at 11:13

2 Answers2

1

will a new StringBuilder(255) be created every time the static Flog.Log() function is called, or will it only be created the first time the method is called?

It will be created every time the static method called Log is called.

Only static members of a class are created once. So if sb would have been a static field of the class, the the StringBuilder would have been created only once.

Christos
  • 53,228
  • 8
  • 76
  • 108
0

according to this post

C# does not support static local variables (variables that are declared in method scope).

Community
  • 1
  • 1
Mohamed Badr
  • 2,562
  • 2
  • 26
  • 43