Can someone help me optimize speed for my code? I tested it via stopwatch in milliseconds. I've implemented my own 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; i++) {
Console.WriteLine(_items[i]);
}
}
public int Add(object value) {
object[] tmp = new object[_items.Length + 1];
for(int i = 0; i < _items.Length; i++) {
tmp[i] = _items[i];
}
tmp[tmp.Length - 1] = value;
_items = tmp;
return tmp.Length - 1;
}
public bool Contains(object value) {
return IndexOf(value) != -1;
}
public int IndexOf(object value) {
return IndexOf(value, 0);
}
public int IndexOf(object value, int startIndex) {
for(int i = startIndex; i < _items.Length; i++) {
if(_items[i].Equals(value)) {
return i;
}
}
return -1;
}
public void Remove(object value) {
if(!Contains(value)) {
return;
}
object[] tmp = new object[_items.Length - 1];
bool deleted = false;
for(int i = 0, j = 0; i < tmp.Length; i++, j++) {
if(_items[i].Equals(value) && !deleted) {
j++;
deleted = true;
}
tmp[i] = _items[j];
}
_items = tmp;
}
public void Insert(int index, object value) {
object[] tmp = new object[_items.Length + 1];
if(index - 1 >= _items.Length + 1 || index < 0) {
Console.WriteLine("This type of index was not found in array");
return;
}
for(int i = 0, j = 0; i < tmp.Length && j < _items.Length; i++, j++) {
if(j == index - 1) {
tmp[j] = value;
i++;
}
tmp[tmp.Length - 1] = value;
tmp[i] = _items[j];
}
_items = tmp;
}
public void RemoveAt(int index) {
if(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
}
}