FIre Panda
FIre Panda

Reputation: 6637

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?

Upvotes: 1

Views: 192

Answers (4)

misosim
misosim

Reputation: 11

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)

Upvotes: 1

phoog
phoog

Reputation: 43066

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.

Upvotes: 0

Emond
Emond

Reputation: 50702

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.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755457

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.

Upvotes: 4

Related Questions