473,583 Members | 4,428 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

List<T> Question

I have been using List(of String) when I could easily be using a string array
instead.

Is it still considered best practice to use Generic list of string rather
then a string array?
Thanks
Mar 23 '06 #1
18 1890


Sean wrote:
I have been using List(of String) when I could easily be using a string array
instead.

Is it still considered best practice to use Generic list of string rather
then a string array?


Use whatever suits the occasion.

The most important difference is that string[] is fixed-length and
List<string> is variable-length.

Remember that they can both be used iterchangeable after creation
through IList<string>.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Mar 23 '06 #2
One more important difference:
The string array gives you insertion cost of O(1),
and array list of type string insertion cost is O(n).
So, string array gives better performance, but is less comfortable to use.
Sharon.

"Helge Jensen" <he**********@s log.dk> wrote in message
news:Om******** ******@TK2MSFTN GP10.phx.gbl...


Sean wrote:
I have been using List(of String) when I could easily be using a string
array
instead.

Is it still considered best practice to use Generic list of string rather
then a string array?


Use whatever suits the occasion.

The most important difference is that string[] is fixed-length and
List<string> is variable-length.

Remember that they can both be used iterchangeable after creation
through IList<string>.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Mar 23 '06 #3
> array list of type string insertion cost is O(n)

Really? Why? Where is that information from?

So far as I know, ArrayList insertion cost is O(1), unless the
ArrayList is full, in which case it must be reallocated elsewhere and
copied to increase its capacity. So, it all rather depends upon whether
it's instantiated (at least) large enough in the first place.

I thought that ArrayList is backed by an array and a "used length", and
the array is simply copied to a bigger array when it gets full.

For a traditional linked list, the insertion cost is typically also
O(1), but the seek cost (for linkedList[i]) is O(n).

Mar 23 '06 #4


Sharon wrote:
One more important difference:
The string array gives you insertion cost of O(1),
A string-array doesn't support "inserting" , it has constant size.
and array list of type string insertion cost is O(n).
yes, insertion is expensive on AraryLists, but appending isn't. And you
can probably use Append and later do .Reverse if needed.

If you allocate the array with a certain capacity the .Add upto that
limit are certainly O(1).

I think -- but haven't actually tested -- that .Add in arraylists are
amortized O(1). I havent had any performance problems filling lists with
100s of thousands of entries, so I find it hard to believe that
ArrayList.Add has complexity O(n).
So, string array gives better performance, but is less comfortable to use.


If perfomance is the issue, use a profiler to find the problems. Don't
micro-optimize.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Mar 23 '06 #5
> yes, insertion is expensive on AraryLists, but appending isn't.

Yes... silly me. I was thinking of appending when I wrote my post. But
then, inserting into the middle of an array (assuming it doesn't have
to grow, which it can't) is the same cost as inserting into an
ArrayList. So far as I know they're the same data structure under the
covers.
If perfomance is the issue, use a profiler to find the problems. Don't micro-optimize.


Amen. Too many programmers think they're being clever by using obscure
constructs to be more "efficient" when in fact their programs are
spending 90% of their time elsewhere.

Mar 23 '06 #6

"Helge Jensen" <he**********@s log.dk> wrote in message
news:OR******** ******@TK2MSFTN GP12.phx.gbl...


Sharon wrote:
One more important difference:
The string array gives you insertion cost of O(1),
A string-array doesn't support "inserting" , it has constant size.


I used the wrong word here.
By inserting i mean: string[1] = value.
Not creating a new element.
and array list of type string insertion cost is O(n).
yes, insertion is expensive on AraryLists, but appending isn't. And you
can probably use Append and later do .Reverse if needed.


Append??

If you allocate the array with a certain capacity the .Add upto that
limit are certainly O(1).
True.
About Add method at msdn:
If Count is less than Capacity, this method is an O(1) operation. If the
capacity needs to be increased to accommodate the new element, this method
becomes an O(n) operation, where n is Count.

I think -- but haven't actually tested -- that .Add in arraylists are
amortized O(1). I havent had any performance problems filling lists with
100s of thousands of entries, so I find it hard to believe that
ArrayList.Add has complexity O(n).
But it does, when Count == Capacity.
So, string array gives better performance, but is less comfortable to
use.
If perfomance is the issue, use a profiler to find the problems. Don't
micro-optimize.


It really depends, if the array is fixed size, then there is no need to use
ArrayList.
I thinks it's better to understand how a collection works, than later change
the implementation
because the profiler shows a problem.
Sharon.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-

Mar 23 '06 #7
The Generic LinkedList class can perform inserts and other tasks with the
same 0(1) performance.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.

"Sharon" <no*****@null.v oid> wrote in message
news:OS******** ******@TK2MSFTN GP11.phx.gbl...

"Helge Jensen" <he**********@s log.dk> wrote in message
news:OR******** ******@TK2MSFTN GP12.phx.gbl...


Sharon wrote:
One more important difference:
The string array gives you insertion cost of O(1),


A string-array doesn't support "inserting" , it has constant size.


I used the wrong word here.
By inserting i mean: string[1] = value.
Not creating a new element.
and array list of type string insertion cost is O(n).


yes, insertion is expensive on AraryLists, but appending isn't. And you
can probably use Append and later do .Reverse if needed.


Append??

If you allocate the array with a certain capacity the .Add upto that
limit are certainly O(1).


True.
About Add method at msdn:
If Count is less than Capacity, this method is an O(1) operation. If the
capacity needs to be increased to accommodate the new element, this method
becomes an O(n) operation, where n is Count.

I think -- but haven't actually tested -- that .Add in arraylists are
amortized O(1). I havent had any performance problems filling lists with
100s of thousands of entries, so I find it hard to believe that
ArrayList.Add has complexity O(n).


But it does, when Count == Capacity.
So, string array gives better performance, but is less comfortable to
use.


If perfomance is the issue, use a profiler to find the problems. Don't
micro-optimize.


It really depends, if the array is fixed size, then there is no need to
use ArrayList.
I thinks it's better to understand how a collection works, than later
change the implementation
because the profiler shows a problem.
Sharon.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-


Mar 23 '06 #8


Sharon wrote:
I used the wrong word here.
By inserting i mean: string[1] = value.
Not creating a new element.


List<T> have exactly the same compleity on assignment.
yes, insertion is expensive on AraryLists, but appending isn't. And you
can probably use Append and later do .Reverse if needed.

Append??


Sorry, I should have said "..you can probably use .Add to append and
later..."
If you allocate the array with a certain capacity the .Add upto that
limit are certainly O(1).


True.
About Add method at msdn:
If Count is less than Capacity, this method is an O(1) operation. If the
capacity needs to be increased to accommodate the new element, this method
becomes an O(n) operation, where n is Count.


However I have never had a problem filling a list, and i've made some
pretty big ones, so an O(n) insert, giving O(n^2) list-filling should
probably have bit me by now.

Lets look at a small test program:

using System;
using System.Collecti ons.Generic;
using System.Collecti ons;

class ArrayListAddCom plexityTest
{
[STAThread]
static void Main(string[] args)
{
int half_count = 10000000;
List<int> l = new List<int>();
DateTime start = DateTime.Now;
for (int i = 0; i < half_count; ++i)
l.Add(i);
DateTime half = DateTime.Now;
for (int i = 0; i < half_count; ++i)
l.Add(i);
DateTime end = DateTime.Now;

Console.WriteLi ne("first half = {0}s, second half = {1}s", (half
- start).TotalSec onds, (end - half).TotalSeco nds);
if (hack)
foreach (int i in l)
Console.WriteLi ne(i);
}
public static volatile bool hack = false;
}

The volatile boolean hack makes sure the compiler or runtime can't
optimize away the actual generation of the list :)

This program terminates with the output:

first half = 0,3605184s, second half = 0,3404896s

Which clearly shows:

1. List<T>.Add is fast enough for most anything
2. List<T>.Add is O(1), no matter what Capacity is used

Actually, it seems like .Add is sublinear, but that's just GC and
realloc messing with you. The figures are *definatly* solid enouogh to
prove that while List<T>.Add is O(n), it is also O(1) on my system,
atleast for upto 10 million ints.
I think -- but haven't actually tested -- that .Add in arraylists are
amortized O(1). I havent had any performance problems filling lists with
100s of thousands of entries, so I find it hard to believe that
ArrayList.A dd has complexity O(n).


But it does, when Count == Capacity.


Well, now it's tested and it's amortized O(1), Capacity doesn't matter.
If perfomance is the issue, use a profiler to find the problems. Don't
micro-optimize.

It really depends, if the array is fixed size, then there is no need to use
ArrayList.
I thinks it's better to understand how a collection works, than later change
the implementation
because the profiler shows a problem.


I agree that it's good to know how collections works, but just use
whatever's most handy untill there is actually a problem.

The tests i've done now shows clearly that using [] over IList<T> should
probably not be done for performance reasons anytime.

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Mar 24 '06 #9


Kevin Spencer wrote:
The Generic LinkedList class can perform inserts and other tasks with the
same 0(1) performance.


At the expense of having lookup: this[int index] worst-case and expected
complexity O(n) ;)

--
Helge Jensen
mailto:he****** ****@slog.dk
sip:he********* *@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Mar 24 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
5603
by: Dave | last post by:
Hello all, After perusing the Standard, I believe it is true to say that once you insert an element into a std::list<>, its location in memory never changes. This makes a std::list<> ideal for storing vertices of an arbitrary n-ary tree where a vertex contain pointers to its parent / children. These parent / child vertices need to stay put...
4
2467
by: Mikhail N. Kupchik | last post by:
Hi All. I have a question regarding C++ programming language standard. It is related to standard library, not to the core language. Is it portable to instantiate template class std::list<> with incomplete type? I've seen some STL implementations which allow this and some others that does not. I did not find any mentioning of this topic...
4
52953
by: matty.hall | last post by:
I have two classes: a base class (BaseClass) and a class deriving from it (DerivedClass). I have a List<DerivedClass> that for various reasons needs to be of that type, and not a List<BaseClass>. However, I need to cast that list to a List<BaseClass> and it is not working. The code is below. I get the following exception: "Unable to cast...
9
7872
by: Paul | last post by:
Hi, I feel I'm going around circles on this one and would appreciate some other points of view. From a design / encapsulation point of view, what's the best practise for returning a private List<as a property. Consider the example below, the class "ListTest" contains a private "List<>" called "strings" - it also provides a public...
0
1739
by: Iron Moped | last post by:
I'm airing frustration here, but why does LinkedList<not support the same sort and search methods as List<>? I want a container that does not support random access, allows forward and reverse traversal and natively supports sorting, i.e., STL's list<T>. There isn't even a set of algorithms that would allow me to easily sort a generic...
7
57532
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any way to convert from a dictionary to a list without itterating through the entire collection and building up a list? 2. is there a common base class, collection or interface that can contain...
44
39149
by: Zytan | last post by:
The docs for List say "The List class is the generic equivalent of the ArrayList class." Since List<is strongly typed, and ArrayList has no type (is that called weakly typed?), I would assume List<is far better. So, why do people use ArrayList so often? Am I missing somehing? What's the difference between them? Zytan
45
18826
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
35
5863
by: Lee Crabtree | last post by:
This seems inconsistent and more than a little bizarre. Array.Clear sets all elements of the array to their default values (0, null, whatever), whereas List<>.Clear removes all items from the list. That part makes a reasonable amount of sense, as you can't actually take items away from an Array. However, there doesn't seem to be a way to...
9
6171
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I've an optimization question for you all really quick. I have a stream that I am reading some bytes. At times, the stream can contain a small amount of bytes such as 50 or so or it can contain as much 10000000 bytes. In reality, I do not know the maximum number of bytes. In my function, I am going to read() the...
0
7825
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8179
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7933
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6578
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5700
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3841
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2331
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1431
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1155
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.