I'm currently reading the (generally excellent) CLR via C#, and I've recently hit the section on boxing. Why is it that authors feel they have to scaremonger about the effects boxing can have on performance?
Here's a piece of code from the book:
using System;
public sealed class Program {
public static void Main() {
Int32 v = 5; // Create an unboxed value type variable.
#if INEFFICIENT
// When compiling the following line, v is boxed
// three times, wasting time and memory
Console.WriteLine("{0}, {1}, {2}", v, v, v);
#else
// The lines below have the same result, execute
// much faster, and use less memory
Object o = v;
// No boxing occurs to compile the following line.
Console.WriteLine("{0}, {1}, {2}", o, o, o);
public sealed class Program {
public static void Main() {
Int32 v = 5; // Create an unboxed value type variable.
#if INEFFICIENT
// When compiling the following line, v is boxed
// three times, wasting time and memory
Console.WriteLine("{0}, {1}, {2}", v, v, v);
#else
// The lines below have the same result, execute
// much faster, and use less memory
Object o = v;
// No boxing occurs to compile the following line.
Console.WriteLine("{0}, {1}, {2}", o, o, o);
No comments:
Post a Comment
Post your comments here: