创建对象的最佳实践应用于对/ foreach循环 [英] Best practice for creating objects used in for/foreach loops

查看:100
本文介绍了创建对象的最佳实践应用于对/ foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
什么是与对象为或foreach循环处理的最佳做法?我们应该创建环路外一个对象,并从头再来重新创建(使用新的...)或建立每次循环新的结果
?例如:


What's the best practice for dealing with objects in for or foreach loops? Should we create one object outside the loops and recreate it all over again (using new... ) or create new one for every loop iteration?
Example:

foreach(var a in collection)
{
  SomeClass sc = new SomeClass();
  sc.id = a;
  sc.Insert();
}

SomeClass sc = null;
foreach(var a in collection)
{
  sc = new SomeClass();
  sc.id = a;
  sc.Insert();
}



哪家好?

Which is better?

推荐答案

第一种方法是更好,因为它更清楚地传达了变量的预期范围,并防止错误意外使用预定范围以外的对象

The first way is better as it more clearly conveys the intended scope of the variable and prevents errors from accidentally using an object outside of the intended scope.

原因之一为希望使用第二种形式是,如果你想打出来的循环,还是要你在循环最后来到了对象的引用。

One reason for wanting to use the second form is if you want to break out of the loop and still have a reference to the object you last reached in the loop.

一个坏之所以选择第二种形式是性能。这可能乍一看似乎是第二种方法使用较少的资源,或者你只创建一个对象和重用它。这不是这里的情况。一个变量的循环中反复声明不消耗任何额外的资源或时钟周期,这样你就不会从拉环外的申报获得任何性能优势。

A bad reason for choosing the second form is performance. It might seem at first glance that the second method uses fewer resources or that you are only creating one object and reusing it. This isn't the case here. The repeated declaration of a variable inside a loop doesn't consume any extra resources or clock cycles so you don't gain any performance benefit from pulling the declaration outside the loop.

这篇关于创建对象的最佳实践应用于对/ foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆