Dictionary Performance
Whats the difference between the teo snippets?
Snippet 1:
{
Dictionary<MyCLass, bool> dic;
开发者_运维知识库MyFunc(out dic);
}
Snippet 2:
{
Dictionary<MyCLass, bool> dic = null;
MyFunc(out dic);
}
Is snippet 2 better in performance?
Technically speaking the second code snippet will likely execute more instructions than the first by doing a redundant null
set. I'm hedging with likely here because the C# spec may allow for the flexibility of ignoring this set. I don't know off hand.
However I would seriously doubt that would ever noticeably affect performance of an application. I certainly would not code for that optimization but would instead prefer the solution which I found more understandable.
Do not worry about these when you haven't measured the performance of the application.
Things like this are very unlikely to have a huge impact, in fact, most of the time things like this will not be noticeable compared to other lines you wrote.
Measure first, them worry about performance.
I like snippet 2, it's slower but better practice to reduce errors, overall a good habit to have - to init variables explicitly. Maybe even the JIT can optimize it away at access time so you only lose a little bit of performance at compile & load time not at execution (but I haven't verified this debugger/disassembler but the JIT is quite 'smart' for a computer program so it maybe able to do it)
Compile them both and compare the IL. I imagine it would be the same. The storage for the out parameter should be initialized to zero (null, if it is a reference type) before it its passed to the called method.
精彩评论