Prev | Current Page 141 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

In other words, the casts we??™ve been putting
in our C# 1 code have always worked in my experience. Those casts have
been like warning signs, forcing us to think about the type safety explicitly
rather than it flowing naturally in the code we write. Although generics
may not radically reduce the number of type safety bugs you encounter,
the greater readability afforded can reduce the number of bugs across
the board. Code that is simple to understand is simple to get right.
All of this would be enough to make generics worthwhile??”but there are performance
improvements too. First, as the compiler is able to perform more checking, that leaves
less needing to be checked at execution time. Second, the JIT is able to treat value types
in a particularly clever way that manages to eliminate boxing and unboxing in many situations.
In some cases, this can make a huge difference to performance in terms of
both speed and memory consumption.
Many of the benefits of generics may strike you as being remarkably similar to the
benefits of static languages over dynamic ones: better compile-time checking, more
information expressed directly in the code, more IDE support, better performance.
The reason for this is fairly simple: when you??™re using a general API (for example,
ArrayList) that can??™t differentiate between the different types, you effectively are in a
dynamic situation in terms of access to that API.


Pages:
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153