这是克隆 C# 数组列表的最快方法
由于主题行几乎清楚地表明了这一点,我想知道如果我在重写的 Clone() 方法中执行其中任何一个操作,克隆普通数组列表会产生什么区别。
MyArraylist 只是普通数组列表的衍生版本。
选项 1
return new MyArraylist(this);
选项 2
MyArraylist temp = new MyArraylist();
temp = (MyArraylist)this.Clone();
return temp;
其中 this 指的是需要克隆的焦点 Arraylist。 我的 arraylist 类有一个重载的构造函数,
public MyArrayList(MyArrayList oArrayList)
{
lock (oArrayList.SyncRoot)
{
foreach (object oObject in oArrayList)
{
if (oObject is ICloneable)
{
this.Add(((ICloneable)oObject).Clone());
}
else
{
this.Add(oObject);
}
}
}
}
如果我使用选项 1 中的方法来获得相对较大的列表,是否会导致性能下降?
希望我很清楚
As the subj line makes it almost clear, i want to know what difference would cloning of a normal arraylist make if i do either of these in my overriden Clone() method.
MyArraylist is simply a derivative of a normal arraylist.
OPTION 1
return new MyArraylist(this);
OPTION 2
MyArraylist temp = new MyArraylist();
temp = (MyArraylist)this.Clone();
return temp;
where this refers to the Arraylist in focus which needs to be Cloned.
and my arraylist class has an overloaded constructor
public MyArrayList(MyArrayList oArrayList)
{
lock (oArrayList.SyncRoot)
{
foreach (object oObject in oArrayList)
{
if (oObject is ICloneable)
{
this.Add(((ICloneable)oObject).Clone());
}
else
{
this.Add(oObject);
}
}
}
}
Is there a performance hit that is incurred if i use as in OPTION 1. for a relatively bigger list?
Hopefully i'm clear
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您发布代码后,我认为您正在比较仅克隆数组列表(选项 1)与克隆数组列表加上克隆数组列表内的任何可克隆对象。
编辑:数组列表只是一个包含引用的对象。因此 new 只是创建一个新的数组列表。所以你有 2 个数组列表和 x 个对象。第二个选项将创建一个新的数组列表并克隆引用的对象,因此您将需要 2 个数组列表和 2*x 个对象。
如果您需要选项 1 还是选项 2,这取决于您的要求。选项 1 总是会更快,因为它的工作量更少。
After you have posted your code, I think you are comparing cloning solely the Array list (option 1) vs cloning the array list plus cloning any cloneable object inside the Array list against each other.
Edit: The array list is just an object on its own containing references. Thus a new just creates a new array list. So you have 2 array lists and x objects. The second option will create a new array list and will clone the refered objects as well, thus you will have to 2 array lists and 2*x objects.
It depends on your requirements, if you need option 1 or option 2. Option 1 will always be faster as it is less work.