예제문과 기술내용은 해석보다는 바로 보시고 이해할 만한 수준이기에 구조체에 관한 몇 줄만 번역 했습니다.

구조체를 사용하는 이유로 프로그램의 성능 향상과 깔끔한 코드를 원하기 때문일 것이다. 뿐만 아니라 구조체는 일부 상황에서 클래스 보다 나은 혜택을 제공한다. 물론 여기에는 문제점도 있지만 클래스와 구조체를 잘 혼합하여 사용한다면 개발 시간 단축과 프로그램 효율에 도움이 될 것이다.

여기 몇 가지 예제들과 함께 벤치마킹 데이터가 있으니 참고하기 바란다.

C#에서의 구조체란?
우선 구조체란 각각의 필드에 동일하게 사용자가 원하는 타입의 값을 저장 할 수 있도록 만들어 준다. 이때 데이터의 참조로 저장되는 것이 아니라 문자열 안의 문자배열과 동일한 형태로 저장된다.

MSDN에 의하면 구조체는 힙 얼로케이션이션(할당)을 요구하지 않는다고 한다. 이 말은 클래스 타입의 변수가 데이터를 참조하는데 반해 구조체 타입의 값들은 곧바로 데이터 구조를 포함한다는 것이다. 즉 구조체를 통해 C#에서 객체가 넘치는 것을 피할 수 있다.

(이 부분의 번역이 매끄럽지 않다. 추가 설명 하자면, 클래스는 인스턴스를 만들어 그 객체를 참조하도록 만드는데 이때 힙 부분에 그 참조 되는 부분이 올라가고 일정부부 사용이 되지 않을 때 가비지컬렉터에 의해 제거 되는데, 가비지컬렉터 사용은 결국 성능에 도움이 되지 않기 때문에 구조체를 통해 그 클래스 객체 생성을 막을 수 있고 성능에 도움이 된다는 뜻으로 해석 된다.)

아래 글 주소: http://dotnetperls.com/Content/Struct-Examples.aspx

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. Solution. I have prepared examples and benchmarks here.

1. What structs are in C#
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." [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.

2. Using a struct and debugging it
This example console program uses a struct called Simple, which stores three values itself: two numbers and a boolean.

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".



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.

●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.
●Use structs with databases.
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: http://msdn.microsoft.com/en-us/library/aa664482(VS.71).aspx]

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.

using System;

class Program
{
    static void Main()
    {
        // Initialize to 0.
        S st = new S();
        st.X = 5;
        Console.WriteLine(st.X);
        // 5
    }

    struct S
    {
        int _x;
        public int X
        {
            get { return _x; }
            set
            {
                if (value < 10)
                {
                    _x = value;
                }
            }
        }
    };
}

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.

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#: http://www.codeproject.com/KB/cs/structs_in_csharp.aspx]


 Class version  Struct version

 class Program
{
    class C
    {
        public int X;
        public int Y;
    };

    static void Main()
    {
        C local = new C();
        local.X = 1;
        local.Y = 2;
    }
}

 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: http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx]

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.



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.



 Version  Size of List<> Size of internal array 
 Class 1 object
512 KB
100000 objects
3.8 MB
 Struct 1 object
24 bytes
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  Structs tested
 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;
};
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;
};
class S
{
    public string A;
    public string B;
    public string C;
    public string D;
}
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.



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.

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.

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
C# 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.

Posted by Jake Kim
TAG c#, struct

C# 정렬하기 2탄

.NET 2009/03/05 20:02
OrderBy와 LINQ를 이용한 정렬
Posted by Jake Kim

Generics 이란?

JAVA를 주로 사용했던 이유로 범용 메소드를 만들 때면 object로 저장 하는 방법을 많이 이용했다. 이렇게 하면 데이터 타입에 연연하지 않고 파라메터로 넘길 수 있기 때문이다. 물론 동일한 이름의 메소드를 만들 때 파라메터에 의해 결정되는 오버로딩 방법도 있지만 단순히 범용 메소드를 만들 때면 object를 보내는 방법을 선호 했다.

지금까지 object는 가장 상위에 있기 때문에 모든 개체를 받을 수 있고 활용할 수 있기 때문에 편리하다고만 생각 했지 이를 사용함으로써 발생되는 문제는 생각해보지 않았다. 특히 C++의 템플릿방식이 더 귀찮다고 생각 했는데 C#을 배우면서 C++의 템플릿 방법에 대해 다시 한번 생각 해보게 되었고 그 이유로 이 글을 작성한다.

참고로 JAVA에도 Generics라는 기능이 있다. 다만 1.5버전 부터 추가된 기능으로 1.3부터 자바를 써왔던 나는 Generics라는 기능에 대해 깊이 고민해 본적이 없다. 어찌 되었든 C#에서도 Generics라는 기능이 추가 되었고 이 부분은 한번쯤 짚고 넘어 가는게 좋을듯 하다.

우선 C# 2.0에서 가장 기대 되는 기능 중 하나가 Generics라고 한다. JAVA에 저 Generics라는 기능이 나왔을때 말이 많았는 C#에서 조차 이 기능이 추가된걸 보면 C++의 템플릿 기능이 프로그래밍에 여러모로 도움이 되나 보다.

Generics를 사용하는 이유?

MSDN에 따르면, generics를 사용하면 실제 데이터 형식을 커밋 하지 않고도 형식이 안전한 데이터 구조를 정의할 수 있고, 형식별 코드를 복제하지 않고도 데이터 처리 알고리즘을 다시 사용할 수 있기 때문에 성능이 크게 향상되고 코드의 품질이 높아진다고 한다. 개념적으로 generics는 C++ 템플릿과 비슷하지만 구현 및 성능 면에서는 크게 다르다고 하는데 그 부분에 대해서는 설명할 부분이 너무 많아 지기 때문에 여기서는 설명 하지 않도록 하겠다.

자 그렇다면 여기서 말하는 중복을 피하고 성능이 올라가고 코드의 품질이 올라간다는 말은 무엇일까? C++을 해봤다면 알겠지만 템플릿은 꽤나 유용하다. 무형의 데이터 타입을 정의하고 컴파일 할 때 구현되도록 함으로써 소스코드의 중복을 피하고 코드 품질이 좋아진다고 볼 수 있다. 하지만 여기서 말하는 성능이란 무엇일까? 사실 나는 object로 처리 하는 게 낫다고 생각 했는데 MSDN을 보니 여기도 문제가 있는 것 같다.

우선 기본적으로 개체 기반 솔루션에는 두 가지 문제가 있다고 한다. 첫 번째는 성능이다. 값 형식을 지정하지 않고 object로 처리 할 경구 힙의 부담이 늘어나고 성능에 좋지 않은 영향을 주는 가비지컬렉터의 증가로 이루어진다는 것이다. 또한 값 형식 대신 참조 형식을 사용하는 경우에도 개체에서 상호 작용하고 있는 실제 형식으로 캐스팅해야 하고 캐스팅에 따른 추가 작업이 필요하므로 성능이 저하 된다고 한다.

나는 지금까지 JAVA의 가비지컬렉터를 너무 맹신했는지 모르겠다. 물론 지금까지 해왔던 모든 코딩을 하나로 합친다고 하더라도 큰 무리는 없겠지만 앞으로는 이런 부분까지 고려 해야 할 듯 하다.

참고로 잘 이해가 되지 않는 분들은 DB의 TABLE을 설계 할 때 각각의 타입을 정하고 그 크기까지 정확하게 맞춰서 생성하는 것과 같은 맥락이라고 보면 쉽게 이해 될 것이다.
(사실 TABLE 설계도 숫자랑 문자랑 구분 짓고 그냥 냅다 255자까지 들어 가게 해버린 나를 생각 하면 object를 쓰면서 힙을 생각 한다는 게 더 이상했는지도 모르겠다.)




사실 이런 부분을 피하기 위해 각각의 메서드를 만들어 구현할 수 있지만 이렇게 될 때 중복되는 코드가 많아진다는 것이다. C++을 제대로 공부 해봤다면 C#의 generics을 바로 이해 했겠지만, 이제 서야 generics의 기능을 알게 되었다.


C# Generics
참고: http://msdn.microsoft.com/ko-kr/library/ms379564(VS.80).aspx

사실 제 글을 보는 것 보다 MSDN을 보는 게 훨씬 나을 듯 합니다. 글 재주도 없고 본래 있는 글을 다시 풀어서 설명하다 보니 누락 되거나 잘못 언급 된 곳도 있으리라 생각합니다.
어찌 되었든 C#의 generics 기능을 사용하여 구조체를 만들어 자신만의 타입을 사용할 때는 꽤나 강력한 기능이 될 것 같습니다. 거기다 LINQ를 통한 프로그래밍 자체의 SQL문을 사용할 수 있으니 배열 처리시 정렬 등에 굉장히 효과가 있을 듯 합니다.
Java Generics
참고: http://today.java.net/pub/a/today/2003/12/02/explorations.html

Posted by Jake Kim
TAG c#, Generics

C#에서의 VAR 타입

.NET 2009/02/26 16:31

각 언어마다 특징이 있겠지만 C#은 특히나 복합적이면서 독특한 기능을 많이 제공하는 것 같다. Visual studio 2003때 C#을 사용해봤으니 꽤나 오래 되었지만, 당시로서도 꽤나 능동적이면서 편리한 기능을 제공했다. 사실 당시 나는 C#보단 자바가 좋았다. 물론 그때 자바를 주로 사용했던 이유도 있겠지만, 자바는 이미 완성이 되어 있는 언어라면 C#은 아직 갈 길이 멀어 보이는 언어 같았기 때문이다.

어찌되었던 오랜만에 프로그래밍을 다시 시작하면서 잡은 언어가 C#이다. 뿐만 아니라 앞으로도 계속 공부 해야 할 분야가 .NET이다 보니 꽤나 바빠질 듯 하다.

그럼 C#을 특징들을 적어 보도록 하겠다.
What is “VAR” the type in new C#?? (http://msdn.microsoft.com/ko-kr/library/bb384061.aspx)

VAR 타입을 모르는건 아니지만 내가 C#을 했을 때 는 분명 없었던 타입이었다. 아니면 당시로서는 별로 관심이 없었거나.

이 VAR타입이 자바스크립트의 VAR타입과는 어떻게 다른지는 아직 모르겠지만 기본적으로 타입 뒤에 나오는 형식에 맞춰 타입이 정해지는 원리는 같으리라 본다.

그럼 왜 C#에서 이 VAR 타입이 갑자기 나온 것일까?
우선 var타입은 변수에 저장되는 값을 보고 타입형식이 정해지므로 사용성 면에서는 편하다. 그리고 배열값 같은 것을 바로 넣어서 foreach문에서 돌릴 수 있기 때문에 반복문 에서도 효과가 있다. 하지만 단순히 이런 이유 때문일까? 그래서 좀 알아 봤다.

What is the purpose of var type? (http://blogs.msdn.com/danielfe/archive/2005/09/22/472884.aspx)

우선 C# 개발자들은 저장되는 타입에 관계없이 언어에 통합된 쿼리라는 LINQ를 추가했다.
타입에 관계가 없다는 것은 그것이 OBJECT던 XML이던 SQL이던 관계없이 쿼리 문처럼 사용하겠다는 말이다.

근데 이 LINQ에는 문제가 있는데 그것이 LINQ로 조회한 값의 타입이 정형적이 안타는 것이다. 즉 프로그래밍 안에서 SQL의 쿼리 문처럼 사용해서 반환되는 것을 저장하려다 보니 프로그래머가 일일이 반환되는 타입에 맞춰 변수 타입을 설정 하기가 힘들다는 것이다. 그래서 나온 것이 VAR타입이란다.  반환되는 타입에 맞춰 컴파일러가 타입을 설정 하다보니, 사실 사용에는 무척 편하다. 변수 타입 생각 안하고 막 코딩 해도 되는 PHP같으니 말이다.
그런데 여기에는 단점이 있다. PHP를 해본 사람은 알겠지만 변수가 많아지고 처리해야 데이터가 많아지다 보면 가장 어려운 것이 자신이 만든 변수의 타입을 잊어 버린다는 것이다. 물론 큰 문제는 아닐지도 모르지만 코드 가독성 에서는 최소한 득보다는 실이 많다는 얘기다.

결과적으로 사용에는 편리성이라는 무기가 더 늘어 났지만, 자칫 VAR를 남발하여 프로그래밍을 하다 보면 가독성 및 일관성에는 문제가 될 것이다.


LINQ에 대해 더 자세히 알고 싶다면 아래 링크를 클릭~
LINQ 프로젝트: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

Posted by Jake Kim
TAG c#, var

Php의 장점 가운데 하나는 배열 사용이 참 용이 하다는 점입니다. 키와 값으로 매칭하기도 쉬울 뿐만 아니라 다양한 함수가 제공되기 때문에 사용이 참 편합니다.

오늘 작업 중 이 배열 키와 값을 가지고 함수를 하나 만들어 달라는 부탁을 받고 부랴부랴 C#의로 작업 했던 내용입니다. 저는 주로 JAVA, JSP, PHP를 해왔기 때문에 C#에 관해서는 지식이 부족합니다. 그래서 제가 소개하는 방법이 좋은 방법인지 아닌지는 알 수 없지만 정보 공유 차원에서 올려 둡니다.


System.Collections.Generic.Dictionary 의 클래스를 사용하도록 하겠습니다. 참고로 Dictionary 클래스는 Hashtable이나 Hashmap과 비슷하다고 생각하시면 됩니다. 저는 C#의 다른 방법을 잘 알지 못해 이 방법을 사용했습니다.




참고: http://weblogs.asp.net/mehfuzh/archive/2008/06/17/replace-sorteddictionary-with-linq-query.aspx
http://en.csharp-online.net/BCL_Generics%E2%80%94Dictionary_TKey%2C_TValue
http://stackoverflow.com/questions/289/how-do-you-sort-a-c-dictionary-by-value


Posted by Jake Kim


친구중 한명이 자바를 공부하고 있다네요.
갑자기 예전 생각도 나고 어설프게 만들었던 프로그램도 생각나서 하나 올려봅니다.
물론 이 프로그램은 자바가 아닌 C#으로 만들어졌습니다.

사실 이와 동일한 프로그램을 자바로 먼저 만들었지만 그 소스는 너무오래되서 찾을 수가 없더군요.
결구 그후 C#으로 만든 프로그램을 올려봅니다.
참고로 이 프로그램역시 인스톨버전만 남아있고 소스는 남아 있지 않네요.

ChangedFileName_Setup.zip <- 디버깅전에 저장한 소스같습니다.
대략적인 구조 파악은 될듯...
따로 로직을 배우지 않아 딱보면 막코딩이라는거 아실수 있을겁니다.


- 작업시기 : 역시나 오래되서 기억안남 2005년인가???
- 작업시간 : 역시나 기억안남 며칠이었지-_-;;;
- 작업언어 : C#
- 개발동기 : 애니메이션 또는 사진등 순차적으로 진행되는 파일이름을 한꺼번에 순차적으로 바꾸고 싶었기 때문
- 설명 : 파일 이름 및 확장자를 전체 또는 개별 변경할수 있는 기능을 갖추고 있음
- 참고 : 닷넷프레임워크 필요합니다.

사용자 삽입 이미지
사용자 삽입 이미지

Posted by Jake Kim