C # efficient programming topic set 2

Source: Internet
Author: User

1: Ensure the thread security of the Set

If. net4.0 is used, a new thread security collection class is available.
The new System. Collections. Concurrent namespace introduces multiple new thread-safe collection classes, which can provide lock-free access to the item at any time as needed and provide fine-grained locking when the lock applies. Using these classes in a multi-threaded solution requires better performance than the set type (for example, ArrayList and List <(Of <(T>.

Except for the set in the System. Collections. Concurrent space
Lock (non-generic set object. SyncRoot) to lock the set thread for security purposes
Generic set usage
Static object sycObj = new object (); // whether the object is static depends on the specific application
Lock (sycObj)
{
// Operation set.
}

2: whether to calculate the length or use list. Count in a loop, which is efficient?

Category 1:

Int len = list. Count;

For (int I; I <len; I ++)

{

Iteration

}

Category 2:

For (int I; I <list. Count; I ++)

{

Iteration

}

The answer is as high.

The first method is completely unnecessary. Many people may think it will bring efficiency to the code, but it will not actually bring any improvement to the efficiency.
As a matter of fact, inside the indexer, the count of the entire list is still calculated for the sake of security. You may better understand this by posting the code of the two:
Public T this [int index]
{
Get
{
If (index> = this. _ size)
{
ThrowHelper. ThrowArgumentOutOfRangeException ();
}
Return this. _ items [index];
}
Set
{
If (index> = this. _ size)
{
ThrowHelper. ThrowArgumentOutOfRangeException ();
}
This. _ items [index] = value;
This. _ version ++;
}
}


Public int Count
{
Get
{
Return this. _ size;
}
}

3: Evaluate the latency

Take List <int> list = new List <int> () {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; as an example, describes the latency and Active Evaluation in the linq query.

List <int> list = new List <int> () {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Var temp1 = from c in list where c> 5 select c;
Var temp2 = (from c in list where c> 5 select c). ToList <int> ();
List [0] = 11;
Console. Write ("temp1 :");
Foreach (var item in temp1)
{
Console. Write (item. ToString () + "");
}
Console. Write ("temp2 :");
Foreach (var item in temp2)
{
Console. Write (item. ToString () + "");
}

4: exercise caution when using static members of the generic type.

Static void Main (string [] args)
{
MyList <int> list1 = new MyList <int> ();
MyList <int> list2 = new MyList <int> ();
MyList <string> list3 = new MyList <string> ();
Console. WriteLine (MyList <int>. Count );
Console. WriteLine (MyList <string>. Count );
}
Class MyList <T>
{
Public static int Count {get; set ;}
Public MyList ()
{
Count ++;
}

}

Code output is Mozi?

As long as you know that MyList <int> and MyList <string> are two different types, it is not difficult to understand this question .. . NET.

5: Be careful with the traps in the closure.

For (int I = 0; I <10; I ++)
{
Action t = () =>
{
Console. WriteLine ("t1:" + I. ToString ());
};
T. BeginInvoke (null, null );
}

The output of the above Code is?

When the closure references external local variables or method parameters, C # will compile the variable into an instance field of the class. The code on the top floor is equivalent:
TempClass tp = new TempClass ();
For (tp. I = 0; tp. I <10; tp. I ++)
{
Action t = tp. TempMethod;
T. BeginInvoke (null, null );
}
TempClass is a class automatically generated by the C # compiler, which is defined as follows:
Class TempClass
{
Public int I;
Public void TempMethod ()
{
Console. Writeline ("t1:" + I. ToString ());
}
}
Because it only loops 10 times, it almost completes in an instant, so the first asynchronous delegate has not started to execute tp. I is equal to 10.

6: Role of the event keyword

Since the delegate can also implement callback, why do we need the event keyword. Q: The biggest function of an event is to prevent class events from being triggered outside the class.

7: distinguish IEnumerable <T> and IQueryable <T>

The local data source uses IEnumerable <T> and the remote data source uses IQueryable <T>.
For LinqLINQ to objects, use the extension method in Enumerable to sort and query local sets. The query parameters accept Func <>. Func <> is called a predicate expression, which is equivalent to a delegate. For LinqLINQ TO to SQL, the extension method in Querable is used. The parameter accepted is Expression <>. Expression <> used to wrap Func <>. The LinqLINQ to SQL engine will eventually convert the expression tree into corresponding SQL statements and then execute them in the database.

8: select the correct set

See this article: html "> http://www.bkjia.com/kf/201104/88261.html

9: should the constraints on generic parameters be better called conventions?

In the process of using generic parameters, a common feature is to set constraints for generic parameters. Constraints seem to limit the scope of use of generic parameters. In fact, constraints themselves actually extend the use of generic parameters.

A non-constrained generic parameter can only have the behavior and attributes of objects, while a generic parameter with the specified constraint as Student can use all the public attributes and methods of the Student type.

Therefore, I think it is really bad to restrict the translation of this word.

10: reduce the use of custom Delegation

The three (or three series) delegates in FCL have already met the needs of most custom delegates, so they basically no longer need custom delegates.

They are:

Action indicates that 0 or more input parameters are accepted, and code is executed, but no return value is returned;

Func indicates accepting 0 or more input parameters, executing a piece of code, and returning values;

Predicate defines a set of conditions and determines whether the parameters meet the conditions;

 

Related Article

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.