简体   繁体   中英

What is the better approach of adding elements to a list C#

I have a list of points which I am using to add points.

I have two approaches but I just want to know which one is better.

Following is the code for first approach:

 List<Point> borderPoints = new List<Point>();

                Point p1 = new Point(0, 0);
                Point p2 = new Point(Width, 0);

                borderPoints.AddRange(new[] { p1, p2 });

in the second approach I add the points like below:

 borderPoints.Add(p1);
 borderPoints.Add(p2);

I have to add the points four times, so which approach I should follow and why, or it doesn't matter, it's just the case of style ?

Definitely choose the first one, where you can. AddRange acts much faster then every single Add . (if you think about list rsize due the growing of the list's collection, it becomes clear)

Use a third approach:

List<Point> borderPoints = new List<Point>(new Point[] {
    new Point(0, 0),
    new Point(Width, 0),
});

You are right. In your situation it is more a case of your programming style.

Add() is simple and convenient in cycles while AddRange() looks more elegant when used at once.

Thinking about performance:

AddRange() adds an array of previously created tree nodes to the collection while Add() adds a new tree node to the collection (MSDN documentation).

So if you are only adding just 4 of nodes or adding nodes infrequently, use the Add() .

1) If you know by advance how many point you gonna add to your list, use the list constructor with a "capacity" parameter.

2) Unless you use it many times, instantiating a new array only to pass points to AddRange is pure waste.

The answer is simple, if you have a range use AddRange and if you have a single item use Add .

But in your case I wouldn't use a list at all. For me it seems like you are missing a concept called BorderPoints. Something like this:

public class BorderPoints {
    public BorderPoints(Point p1, Point p2) {
        _p1 = p1;
        _p2 = p2;
    }
}

Then you can just use that instead of the list.

I would use the second approach.

The first approach instantiates an array unnecessarily, so will be very slightly slower.

Only use AddRange if the items to add are already in a collection (or enumeration).

In general, if you want to squeeze every last nanosecond of performance, you can do so by ensuring the capacity of your list is large enough for all the items you are going to add:

var list = new List<T>(capacity);
... add items ...

or

list.Capacity = capacity;
... add items ...

But copying individual items into an array before adding them to the list gains you nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM