Struct Examples in C#

来源:互联网 发布:中国高铁领跑世界 知乎 编辑:程序博客网 时间:2024/05/21 06:54

Struct Examples in C#

From:http://dotnetperls.com/struct-examples

by Sam Allen - Updated July 9, 2009

Problem. You want to use structs to improve the performance and clarity of your code. Structs have benefits over classes in some situations, but also negatives in the C# programming language. Solution. Here we see several examples and benchmarks of structs in the C# language.

The struct keyword describes a value type in the C# language.    Structs can improve speed and memory usage.    They cannot be used the same as classes.    Collections of structs are allocated together.

1. Using struct

First, here we see a simple example program that uses a struct type in the C# programming language. This example console program uses a struct called Simple, which stores three values itself: two numbers and a Boolean.

=== Program that declares struct (C#) ===class Program{    struct Simple    {        public int Position;        public bool Exists;        public double LastValue;    };    static void Main()    {        Simple s;        s.Position = 1;        s.Exists = false;        s.LastValue = 5.5;    }}

As an aside, there are practical uses to structs and they are an important part of the language. Here's what the Visual Studio debugger shows inside the struct. Note that the struct is the type "Program.Simple".

Struct in Visual Studio debugger

2. Understanding structs

Structs are custom value types that store the values in each field together. They do not store referenced data, such as the character array in a string.

What MSDN says is that structs "do not require heap allocation." It says that variables of struct type "directly contain the data of the struct, whereas a variable of a class type contains a reference to the data." [Structs (C#) - MSDN source]

What that means is that with structs you avoid the overhead of objects in C#. You can combine multiple fields, reducing memory pressure and improving performance.

Value semantics: this term indicates whether the variable is being used like numbers and values are, or as an inherited class. "Complex numbers, points in a coordinate system, or key-value pairs in a dictionary" are included.

3. When you should choose a struct

First, only consider structs in performance-sensitive parts of your program. Points containing coordinates and positions are excellent examples of structs, as is the DateTime struct.

Many times in programs you have small classes that really serve as collections of related variables you store in memory. You don't have inheritance or polymorphism. These often make ideal structs.

Possible uses. Use structs for offsets. Structs are useful for storing coordinates of offsets in your files. These usually contain integers. Use structs for graphics. When using graphics contexts, use structs for points and coordinates.

Database uses. MSDN provides an example of a nullable integer used for databases. If you don't want to use Nullable<T>, use this. [Database Integer Type]

4. Use property accessors with structs

Remember that your struct cannot inherit like classes or have complex constructors. However, you can provide properties for it that simplify access to its data.

=== Program that uses property on struct (C#) ===using System;class Program{    static void Main()    {        // Initialize to 0.        S st = new S();        st.X = 5;        Console.WriteLine(st.X);    }    struct S    {        int _x;        public int X        {            get { return _x; }            set            {                if (value < 10)                {                    _x = value;                }            }        }    };}=== Output of the program ===5

5. Stack versus heap allocation

Local value types are allocated on the stack. This includes integers such as "int i" for loops. When you create an object from a class in a function, it is allocated on the heap. The stack is much faster normally. The details of stacks and heaps are out of the scope here, but are worthwhile studying.

Struct type as parameters. Because structs are a value type and therefore inherit System.ValueType, they are copied completely when you pass them as parameters to methods. Therefore, structs will degrade performance when you pass them to methods, particularly if they are not very small. [C# Struct Methods and Parameters, Struct Versus Class - dotnetperls.com]

6. Changing your class to a struct

First, you can't easily change classes that inherit or implement interfaces to structs. You cannot use a custom default constructor on structs, as when they are constructed, all fields are assigned to 0. [Structs in C#]

=== Version of program using class (C#) ===class Program{    class C    {        public int X;        public int Y;    };    static void Main()    {        C local = new C();        local.X = 1;        local.Y = 2;    }}=== Version of program using struct (C#) ===class Program{    struct C    {        public int X;        public int Y;    };    static void Main()    {        C local;        local.X = 1;        local.Y = 2;    }}

Struct usage tip: You don't have to instantiate your struct with the new keyword. It works like an int, instead, which means you can access it directly without allocating it explicitly.

7. Can I compare my struct against null?

No. You should think of structs as ints or bools. You can't set your integer variable to null. Nullable types, however, are a generic type that you can use with databases and declare null ints. [Nullable Types - MSDN]

Interestingly, nullable types themselves (System.Nullable) are implemented with structs. The link to Database Integer Type is similar.

8. Memory benchmarks of structs

I looked at the memory layout of the console program in the CLRProfiler. This is a free tool by Microsoft that visualizes the memory allocations of .NET programs.

The first picture here is the memory profile of the version that uses classes. It indicates that the List took 512 KB and was 1 object, and internally it stored 100000 objects and took 3.8 MB.

Memory usage of classes

Using structs, CLRProfiler indicates that the List took 24 bytes and contained 1 object of 4.0 MB. That 1 object is an array of 100000 structures, all stored together.

Memory usage of structs
Version:                ClassSize of List:           1 object                        512 KBSize of internal array: 100000 objects                        3.8 MBVersion:                StructSize of List:           1 object                        24 bytesSize of internal array: 1 object                        4.0 MB

What this means is that structs are not stored as separate objects in arrays, but are grouped together. This is possible because they are value types. We see that structs consume less memory.

9. Allocation benchmarks for structs

It was easier to gather speed benchmarks of structs. I compared two classes to two structs. Both pairs of opposites use either 8 ints or 4 strings.

=== Classes tested in benchmark (C#) ===class S{    public int A;    public int B;    public int C;    public int D;    public int E;    public int F;    public int G;    public int H;}class S{    public string A;    public string B;    public string C;    public string D;}=== Structs tested in benchmark (C#) ===struct S{    public int A;    public int B;    public int C;    public int D;    public int E;    public int F;    public int G;    public int H;}struct S{    public string A;    public string B;    public string C;    public string D;}

Recall that because strings are reference types, their internal data is not embedded in the struct. Just the reference or pointer is. I make note here that the performance benefits of structs with strings persists even when their referential data is accessed, as by assignment or appending.

~~~ Struct/class allocation performance timing in C# ~~~    10 million loops of 100000 iterations.    Tests allocation speed of the data structures.    Structs were much faster in both tests.Class with 8 ints:               2418 msStruct with 8 ints:               936 ms [faster]Class with 4 string references:  2184 msStruct with 4 string references:  795 ms [faster]

We see substantial speedups of over two times when allocating the structs. This is because they are value types allocated on the stack. Note they are stored in a List field.

Specific notes: I tried to ensure accuracy of the test by assigning each field and avoiding property accesses, which is why I use public fields.

10. Should I use strings in structs?

Yes, as it can improve performance. However, the struct will not store the string's data. That will be stored externally, where the reference points.

However, using structs can improve performance with the string reference itself. Remember that references are also data that need to be allocated, which we can use struct for.

11. Use struct for ASP.NET website

In my web project, I record thousands of referrer data objects. These store two string fields and a DateTime field. By hovering over DateTime in Visual Studio, you see that it too is a struct.

Because DateTime itself is a struct, it will be stored directly in the struct allocation on the stack. Thus, in a struct with two strings and a DateTime, the struct will hold two references and one value together.

=== Program that uses struct in website (C#) ===using System;using System.Collections.Generic;class Program{    static void Main()    {        var _d = new Dictionary<string, ReferrerInfo>();        // New struct:        ReferrerInfo i;        i.OriginalString = "cat";        i.Target = "mat";        i.Time = DateTime.Now;        _d.Add("info", i);    }    /// <summary>    /// Contains information about referrers.    /// </summary>    struct ReferrerInfo    {        public string OriginalString; // Reference.        public string Target;         // Reference.        public DateTime Time;         // Value.    };}

The optimization in the above code was to replace the class with a struct. This should improve performance by about 2x and reduce memory.

12. Use struct for file offset data

In a database system I developed, file blobs are stored in large files together, and I needed a way to store their offsets. Therefore I had structs with two members: two ints storing positions.

Structs are ideal for this situation: there were 500+ instances of the object, and they only had 2 member fields of value types.

=== Program that uses Dictionary of structs (C#) ===using System.Collections.Generic;class Program{    static void Main()    {        // Stores Dictionary of structs.        var _d = new Dictionary<string, FileData>();        FileData f;        f.Start = 1000;        f.Length = 200;        _d.Add("key", f);    }    /// <summary>    /// Stores where each blob is stored.    /// </summary>    struct FileData    {        public int Start;        public int Length;    }}

13. Notes on pointers and structs

The C# language frees us developers from the nightmare that is C pointers, but understanding pointers is important in performance and language work. Pointers, like references, are values that contain the addresses of data.

C-style pointers are blisteringly fast, but their syntax and lack of error checking causes problems. However, the struct keyword in C# gives us more power over references and how fields are stored.

14. Summary

Here we saw ways you can use structs in the C# language, and also reviewed reasons you will want to. Structs are an advanced topic, but every developer has used them in the DateTime type. Understanding of the value semantics in structs is important to use C# in an efficient and correct way.

原创粉丝点击