Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

c# - Initializing a 'var' to null

Is there any difference in runtime performance between the following variable initializations?

var    x = null as object;
var    x = (object) null;
object x = null;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe no, since there is no difference in compiled IL.

var    x = null as object;
var    x1 = (object)null;
object x2 = null;

gets compiled to

IL_0001:  ldnull      
IL_0002:  stloc.0     // x
IL_0003:  ldnull      
IL_0004:  stloc.1     // x1
IL_0005:  ldnull      
IL_0006:  stloc.2     // x2

You can see all the locals are initialized to null using ldnull opcode only, so there is no difference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...