曾经看过一本书,说在循环中创建对象效率很低。现在我必须在循环中组装对象的组合。如何更改它以提高效率?
我的模型
public class Student
{
public int Age{ get; set; }
public string Name{ get; set; }
public string Sid{ get; set; }
}
我的圈子代码:通过sid获取所有学生
var sidArr="1,2,3,4".split(',');
List<Student> studentes=new List<Student>();
for(int i=sidArr.count();i>=0;i--)
{
Student student=new Student();
student.Sid=i;
var findStudent=student.GetStudentBySid(i);
if(findStudent!=null)
{
student.Name=findStudent.Name;
student.Age=findStudent.Age;
}
studentes.Add(student);
}
我应该将此代码 Student Student=new Student();
放在循环之外吗?如果有很多 sid 来创建很多学生,我应该使用设计模式吗?
最佳答案
您可以像这样实现它(只是不要在循环中执行不必要的操作:例如,创建新的 Student
实例当且仅您必须执行itp> var sidArr = "1,2,3,4".split(',');
List<Student> studentes = new List<Student>();
// 1. Count - 1: do not use Linq when you can use a simple property
// 2. Count - 1: beware range check errors
// 3. foreach(int sid in sidArr) looks much better here
for(int i = sidArr.Count - 1; i >= 0; --i) {
// You should seach by sid, not by index i
int sid = sidArr[i];
var student = student.GetStudentBySid(sid);
if (student == null) {
// If student is not found, we have to create a new instance
student = new Student();
student.Sid = isd; // <- do not forget to set the SID
student.Name = findStudent.Name;
student.Age = findStudent.Age;
}
// Add student: either found or created one
studentes.Add(student);
}
关于c# - 我的代码中哪个代码行为更好?如何更改我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892570/