C # Language Specification--1.8 structure

Source: Internet
Author: User
Specification

Classes and structs have many similarities: structs can implement interfaces and can have the same member types as classes. However, structs differ in several important ways from classes: Structs are value types, not reference types, and structs do not support inheritance. The value of the structure is stored on the stack or inline. Careful programmers can sometimes enhance performance by intelligently using structs.

For example, defining a point as a struct rather than a class can save a lot of memory space at run time. The following program creates and initializes an array of 100 points. For point that is implemented as a class, there are 101 instance objects, because the array requires one, and each of its 100 elements requires one.

Class Point
{
public int x, y;
public point (int x, int y) {
this.x = x;
This.y = y;
}
}
Class Test
{
static void Main () {
Point[] points = new point[100];
for (int i = 0; i < i++)
Points[i] = new Point (i, i*i);
}
}
If you change point to be a struct implementation, such as

struct POINT
{
public int x, y;
public point (int x, int y) {
this.x = x;
This.y = y;
}
}

Only one instance object (the object used for the array) appears. The point instance is allocated inline in the array. This optimization may be misused. Using structs rather than classes also makes your application run slower or consume more memory, because passing a struct instance as a value parameter causes a copy of the structure to be created.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.