Performance hit of checking for null

匆匆过客 提交于 2019-12-01 10:58:34

问题


Can anyone tell me what the performance cost is of checking if an object or property of an object is null in c#? I am working on an ASP.NET MVC application that the null checking is being done in the Model and then done again in the view. I feel that this is excessive but if there is no real performance hit then I don't see the harm in doing things this way.


回答1:


I don't think its measurable if you're doing it just once while rendering and once while initializing the model.

It would have an impact if it were inside a computation-intensive loop though.

Things like querying the database, read/write to files, etc. are the ones you should watch out for.




回答2:


Almost insignificant. Doing this twice is not a problem. Doing it a bajillion times is probably still not a problem (but would be indicative of some other programming issue)




回答3:


Well of course there is SOME performance hit, checking if something is null takes some instructions...

If you'd like to minimize performance hit, use the ILDASM tool to view the CIL code of the method you're using and examine the actual execution path that is taking place. I'd even say: make sure you're using something like Object.ReferenceEquals (as opposed to the instance's Equals method, or the equality operator).



来源:https://stackoverflow.com/questions/12165730/performance-hit-of-checking-for-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!