值类型结构是基于堆栈的变量,它们驻留在处理器缓存而不是RAM中。因此,通过使用值类型变量避免从处理器到RAM的系统总线跳闸应该比使用引用类型变量更快。因此,我没有做stackallock
(Practical use of `stackalloc` keyword),而是创建了一个代表基于堆栈的数组的以下结构:
[StructLayout(LayoutKind.Sequential)]
public struct ArrayOf16Bytes
{
public Byte e0;
public Byte e1;
public Byte e2;
public Byte e3;
public Byte e4;
public Byte e5;
public Byte e6;
public Byte e7;
public Byte e8;
public Byte e9;
public Byte eA;
public Byte eB;
public Byte eC;
public Byte eD;
public Byte eE;
public Byte eF;
public byte this[Int32 index] {
get {
switch (index) {
case 0x0:
return e0;
case 0x1:
return e1;
case 0x2:
return e2;
case 0x3:
return e3;
case 0x4:
return e4;
case 0x5:
return e5;
case 0x6:
return e6;
case 0x7:
return e7;
case 0x8:
return e8;
case 0x9:
return e9;
case 0xA:
return eA;
case 0xB:
return eB;
case 0xC:
return eC;
case 0xD:
return eD;
case 0xE:
return eE;
case 0xF:
return eF;
default:
throw new IndexOutOfRangeException ();
}
}
set {
switch (index) {
case 0x0:
e0 = value;
break;
case 0x1:
e1 = value;
break;
case 0x2:
e2 = value;
break;
case 0x3:
e3 = value;
break;
case 0x4:
e4 = value;
break;
case 0x5:
e5 = value;
break;
case 0x6:
e6 = value;
break;
case 0x7:
e7 = value;
break;
case 0x8:
e8 = value;
break;
case 0x9:
e9 = value;
break;
case 0xA:
eA = value;
break;
case 0xB:
eB = value;
break;
case 0xC:
eC = value;
break;
case 0xD:
eD = value;
break;
case 0xE:
eE = value;
break;
case 0xF:
eF = value;
break;
default:
throw new IndexOutOfRangeException ();
}
}
}
}
case
应该编译为jump table
,因为cmp
和jump
是一个周期的指令(Is there any significant difference between using if/else and switch-case in C#?),第一部分代码应该比第二个
的工作速度比实际数组慢:
[Test]
public void TestStackArrayPerformance() {
var random = new Xor128 ();
byte[] x = new byte[16];
ArrayOf16Bytes p = new ArrayOf16Bytes ();
for (int i = 0; i < 16; i++) {
x [i] = p [i] = random.As<IUniform<byte>> ().Evaluate ();
}
var index = random.As<IUniform<Int32>> ().Evaluate (0, 15);
var timer = DateTime.Now;
for (int i = 0; i < 1000000000; i++) {
var t = x [i & 0xF];
x [i & 0xF] = x [index];
x [index] = t;
}
Console.WriteLine ("Spinup took: {0}", DateTime.Now - timer);
timer = DateTime.Now;
for (int i = 0; i < 1000000000; i++) {
var t = x [i & 0xF];
x [i & 0xF] = x [index];
x [index] = t;
}
Console.WriteLine ("Operation 1 took: {0}", DateTime.Now - timer);
timer = DateTime.Now;
for (int i = 0; i < 100000000; i++) {
var t = p [i & 0xF];
p [i & 0xF] = p [index];
p [index] = t;
}
Console.WriteLine ("Operation 2 took: {0}", DateTime.Now - timer);
}
在我的机器上,这段代码显示以下结果:
Spinup took: 00:00:00.3005500
Operation 1 took: 00:00:00.2959800
Operation 2 took: 00:00:04.4344340
答案 0 :(得分:0)
我不是这个主题的专家,但我相信你有一些错误的假设:
值类型结构是基于堆栈的变量,它们驻留在处理器缓存而不是RAM中。因此,通过使用值类型变量避免从处理器到RAM的系统总线跳闸应该比使用引用类型变量更快。
仅仅因为某些东西是引用类型并不意味着不会使用CPU缓存。堆栈不是可以使用缓存的唯一内存区域。此外,CPU在预读缓存等方面非常聪明,因此您通常不必像这样对内存进行微观管理。
另外,请记住,当您在循环中访问struct
时,您不必担心getter和setter中的指令;每次进行方法调用时都会产生开销,包括索引器。方法调用涉及将参数推送到堆栈,跳转到方法指令,将返回值推送到堆栈,执行返回跳转等等。因此,这比设置一个简单的指令更昂贵也就不足为奇了。数组值。