Why does braces take time on C# code?
Asked Answered
G

1

8

I am using Ants Performance Profiler 8.5 and when I saw the time each row of my code runs, I have noticed that the braces also take time.

Here is an image, you can see at the left of the braces the time in milliseconds:

enter image description here

Sometimes I get more time, like 5 ms...

Why is that? Is it the garbage collection?

Geesey answered 2/6, 2014 at 6:51 Comment(5)
I think your misreading it... return takes 0ms? It is possible though that it is garbage collection (for temp var declaration) but it looks more likely that the time is offsetQuickfreeze
What does the docs say? I can only guess it will be processing of parameters on the stack, preparing the locals on the heap and processing of out parameters and cleanup at the end?Carper
A profiler can only measure the time taken by the machine code produced from your C# code. The mapping from machine code back to C# code isn't always perfect. Particularly when you profile optimized code, like you always should. At the curly braces, there's overhead to setup the stack frame for the method and tear it down again. This takes a few nanoseconds at best, multiplied by the number of times the method gets called. Measuring 5 msec for that is excessive and should be considered "experimental error".Cameo
@Hans That sounds like an answer to me.Leontina
It is a hint, I can't explain 5 msec.Cameo
N
3

When a method is defined, the set of parameters that are in scope for the method are known by the compiler, called a maxstack. This hints at the amount of memory to allocate for the method.

This could be the source of the extra time - memory allocation by the CLR.

Adding more braces doesn't actually add more parameters to maxstack. Its scopes the whole method. Scope is more of a logical grouping, than being implemented by the CLR to release memory.

With your question on GC, I don't believe this is the root-cause of the problem. GC is ran by a separate thread when required. It could be the GC, but I seriously doubt it in your case.

Nitwit answered 3/6, 2014 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.