Is there a performance degradation when we ALWAYS use nullable value types instead of value types?
-
1Overflow : not that you should worry about.– Mitch WheatFeb 5, 2011 at 1:29
-
to point out, I'm willing to bet that @MitchWheat knows a lot more about this than you so I'm gonna go with listen to him. @MitchWheat ~ You should've made that an answer :p ...– jcolebrandFeb 5, 2011 at 1:31
-
1Not as big of a performance hit as having an IStackOverflowUser implementation also inherit StackOverflow itself.– NovikovFeb 5, 2011 at 1:32
2 Answers
As Mitch Wheat pointed about above, no, you should not worry about this. I'm going to give you the short answer reason now, and later I'm going to help you discover more about what you're asking:
Write your code to be correct. Profile after writing so that you find the points that are causing you grief.
When you have code that constantly uses Nullable and you have performance reasons and you profile it and you can't find the problem yourself, then come ask us how to make it faster. But no, the overhead of using Nullable is for all intents and purposes not degrading.
Discover more about what you're asking:
- Performance surprise with "as" and nullable types
- Why shouldn't I always use nullable types in C#
- C# Performance gain returning a Nullable Type from a SqlDataReader
- Alternatives to nullable types in C#
- Casting (int?)null vs. new int?() - Which is better?
- Boxing / Unboxing Nullable Types - Why this implementation?
Now, having read all those pages, I hope you feel more enlightened.
-
1That's an
ul
unordered list -ol
ordered lists are erhn... ordered (numbered) yah know? ;)– Yi JiangFeb 5, 2011 at 2:04 -
-
1What about memory? Since
obj.Value
can't be passed as a reference type (ref/in), it's necessary to assign the value to a new variable, doesn't this necess duplicating the value type as opposed to just assigning it to an ordinary type from the beginning?– kres0345Dec 3, 2021 at 9:14
It's the price of copying the entire value type: pretty much nil for things like integers, GUID's, etc., but it's large if you're constantly copying 512-KB value types (which you shouldn't be having in the first place) inside a tight loop.