patterncsharpMinor
ArrayList implementation
Viewed 0 times
implementationarrayliststackoverflow
Problem
Can someone help me optimize speed for my code? I tested it via stopwatch in milliseconds. I've implemented my own
Mylist.cs
ArrayList and I would like to improve its speed without using C# built-in structures.Mylist.cs
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManualArrayList {
class MyList : IList {
private object[] _items;
public MyList() {
_items = new object[0];
}
public void PrintElement() {
for(int i = 0; i = _items.Length + 1 || index = _items.Length || index < 0) {
Console.WriteLine("This type of index was not found in array");
return;
}
object[] tmp = new object[_items.Length - 1];
for(int i = 0, j = 0; i < tmp.Length; i++, j++) {
if(i == index) {
j++;
}
tmp[i] = _items[j];
}
_items = tmp;
}
public void Clear() {
_items = new object[0];
}
public int Count {
get {
return _items.Length;
}
}
// es avxsnat ertad mere...
public object this[int index] {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
//es ertad gavaketot
public void CopyTo(Array array, int index) {
throw new NotImplementedException();
}
//es ertad gavaketot
public IEnumerator GetEnumerator() {
throw new NotImplementedException();
}
#region We Dont Touch This
public bool IsFixedSize {
get {
return false;
}
}
public bool IsReadOnly {
get {
return false;
}
}
public bool IsSynchronized {
get {
return true;
}
}
public object SyncRoot {
get {
return this;
}
}
#endregion
}
}Solution
Probably the best improvement would be to allocate extra storage space and also store how many elements your list contains. Right now you allocate a new array and copy all existing values on each add operation, and this results in O(n) time complexity for adding items. Instead you could increase inner array twice each time, this would result in amortized O(1). Also, with this approach you wouldn't need to allocate new arrays on removal operations, as you could just leave empty space at the end.
Context
StackExchange Code Review Q#120797, answer score: 6
Revisions (0)
No revisions yet.