1

When accessing an array of objects, I think it is clear to define a variable like 'obj' in the for loops, as follows:

var objects = new object[10000];

//......assign values to objects


//When visiting objects, I think it is clear to define a variable 'obj' in the for loops
for (int i = 0; i < objects.Length; i++)
{
    var obj = objects[i];

    //......visit obj which will be used for many times, so define the obj to simplify the codes

}

But I am concerned with its efficiency. I worry that repeated 'obj' will be created.

Should I define the variable in front of the for loops as follow? As well as defining a variable for objects.Length.

int len = objects.Length;
object obj2;
for (int i = 0; i < len; i++)
{
    obj2 = objects[i];

    //visit obj
    //......
}

Or compiler in Visual Studio will optimize for it?

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
Ken
  • 47
  • 3
  • You might be more interested to see what happens with your second example: [SharpLab](https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYZQAs6AsgBQCU+hxTAbgIYBO6A9gEYBWAUwDGAFwDO6ALzoAdgIDu3fsJEBtOAAYtGgLoBuZIyZEAljJHoANgJlSlg0WIB0AGRsBzEQAsDSY8V4HC0CYX38iADMuTmozCxM7DT10BIAeKxtkkzAwWiNjAj9wphC7QJUxVRN9QyLiogB6BuYTMRNg/nzipqdevq7iAF984br0fLRMCgA5OgYx9DZOcsc7OUUVtU1tGoWomLiUxKz0dM3nNxlPHxScvIXC+qX7MuVHKt2Bxoa+vpa2jp8dDyLwmIReYEmSyWdA8AToACuYgEwHQ+3QAFtWDIAJ7oEQmDECMQAGnQYi46GAAgiZnh3nhgXxlLaGIADpYTBE8Qz0EIuNSxLVjINiCNkIMgA) – ProgrammingLlama Aug 02 '21 at 01:59
  • 2
    In your example above, you are not actually creating new objects, you are creating a reference to an existing object. The creation/allocation has already been done to create the objects array. Your first example will create a new reference each time, the second will create a reference that is persisted outside of the for loop, but you should not notice any significant performance difference between the two. – Xavier Aug 02 '21 at 02:05
  • If the compiler can't prove your accesses are "inbounds" it will insert an expensive runtime check to throw an out of bounds exception. Avoiding that check has the largest potential performance impact. Also, the compiler should be smart enough to hoist those "loop invariants" (eg object.Length) out of the loop. – Jeremy Lakeman Aug 02 '21 at 02:05
  • 2
    Have you considered a `foreach` loop? – mjwills Aug 02 '21 at 02:13

0 Answers0