Which one is better in terms of performance?

What is the difference between these two statements? which is better in performance?

Console.Writeline(i);
Console.Writeline(i.toString());

where i am a string or an integer.

+3
source share
4 answers

The bottom line is that writing to the console should dominate performance here - even if you redirect it to some kind of "empty" receiver.

The difference, IMO, is that

Console.WriteLine(i);

... , , , , . i, , WriteLine(int). :

Console.WriteLine("Some format {0} stuff", i);
Console.WriteLine("Some format {0} stuff", i.ToString());

; . ? .

+14

, ToString .

+2

. Console.WriteLine ToString(), . , IL, , , . , Console.Writeline(int) int , IL...

:

static void Main(string[] args)
{
    int i = 34;
    Console.WriteLine(i);
    Console.WriteLine(i.ToString());

}

IL -

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] int32 i)
    L_0000: nop 
    L_0001: ldc.i4.s 0x22
    L_0003: stloc.0 
    L_0004: ldloc.0 
    L_0005: call void [mscorlib]System.Console::WriteLine(int32)
    L_000a: nop 
    L_000b: ldloca.s i
    L_000d: call instance string [mscorlib]System.Int32::ToString()
    L_0012: call void [mscorlib]System.Console::WriteLine(string)
    L_0017: nop 
    L_0018: ret 
}

Jon ( string.format), ( ToString()) . :

    int i = 34;
    Console.WriteLine(string.Format("Some format {0} stuff", i));
    Console.WriteLine(string.Format("Some format {0} stuff", i.ToString()));

IL

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 2
    .locals init (
        [0] int32 i)
    L_0000: nop 
    L_0001: ldc.i4.s 0x22
    L_0003: stloc.0 
    L_0004: ldstr "Some format {0} stuff"
    L_0009: ldloc.0 
    L_000a: box int32
    L_000f: call string [mscorlib]System.String::Format(string, object)
    L_0014: call void [mscorlib]System.Console::WriteLine(string)
    L_0019: nop 
    L_001a: ldstr "Some format {0} stuff"
    L_001f: ldloca.s i
    L_0021: call instance string [mscorlib]System.Int32::ToString()
    L_0026: call string [mscorlib]System.String::Format(string, object)
    L_002b: call void [mscorlib]System.Console::WriteLine(string)
    L_0030: nop 
    L_0031: ret 
}
+1

Firstly, optimizing this level will really not bring you any benefits. Optimize your algorithms, then profile and optimize your bottlenecks. I would focus on what is more readable and supported (in which I prefer the former, in both cases ...)

However, in terms of performance, the former will usually be better. If you call the first with int, it actually calls the second. Using the string, you get an extra method call (no-op).

0
source

Source: https://habr.com/ru/post/1728946/


All Articles