Performance of an array of structure types

Example:

// Potentially large struct.
struct Foo
{ 
   public int A;
   public int B;
   // etc.
}

Foo[] arr = new Foo[100];

If Foo is a 100-byte structure, how many bytes will be copied to memory during the execution of the following statement:

int x = arr[0].A

That is, arr [0] is evaluated by some temporary variable (100-byte copy of the Foo instance), followed by copying .A to the variable x (4-byte copy).

Or some combination of compiler, JITer and CLR allows you to optimize this statement so that 4 bytes are Acopied directly to x.

If optimization is performed, does it persist when elements are stored in List<Foo>or when an array is passed as IList<Foo>or ArraySegment<Foo>?

+6
source share
2

- . , , . , . , -. , , .

,

struct Foo { public int A; public int B; }

; - , .

Foo f = new Foo();

? :

  • f.
  • temp.
  • temp .
  • temp f.

, ; , , "create f ", . .

: , -elide, , struct.

,

f.A = 123;

f - - A , .

int x = f.A;

f , A , A x.

Foo[] fs = new Foo[1];

fs, , fs.

fs[0].A = 123;

, . f[0] , A , 123 .

int x = fs[0].A;

: fs[0] , A .

List<Foo> list = new List<Foo>();
list.Add(new Foo());
list[0].A = 123;

, list[0] - , . .

int x = list[0].A;

list[0] - , , A x. , .

: , , list[0] , .

(1) (2) . , , , .

, ? ?

. - , 1.

, , ; .

get/set, get , .

, , ,

# 7, #. IL, , , # , .

# 7 : ref . , ref ( out) . # 7 .

+9

. arr[0].A, , . ( , ) arr[0], A , . , A.

, List<Foo> ArraySegment<Foo> .

, arr[0] , Foo. ( ) ( ) .Net; , List<Foo> ArraySegment<Foo> .

.Net, , class struct, . , , , . s > struct, , .

+1

Source: https://habr.com/ru/post/1016864/


All Articles