I've come across some code which could definitely be improved, but i'm wondering about the Big-O notation of my improvements.
Their original code adds a element to an array, and each time it does this it creates a new array of n+1 and copies the old one in like so:
public MyType GetNewType()
{
MyType[] tempTypes = new MyType[_types.Count + 1];
_types.CopyTo(tempTypes, 0);
_types = tempTypes;
_types[types.Count - 1] = new MyType();
return _types[types.Count - 1];
}
As far as I can see this would be a O(n) operation. I therefore rewrote it as follows:
private int _currentIndex; //initialized in the constructor
public MyType GetNewType()
{
if (_types.Length == _currentIndex)
{
MyType[] tempTypes = new MyType[_types.Length + 10];
_types.CopyTo(tempTypes, 0);
_types = tempTypes;
}
_types[_currentIndex] = new MyType();
_currentIndex++;
return _types[_currentIndex - 1];
}
Would the result of these changes mean that the function will now run in O(n / 10) as it would only require a copy operation every 10 calls? Or does it not quite work as nicely as that?