对于时间关键的 C# 代码,我是否应该重视结构中的静态方法(而不是非静态方法)?
For time-critical C# code, should I value static methods in my struct (over non-static ones)?
通过一些研究,我知道下面的静态方法可以使 JIT 内联。但是非静态的也可以内联吗?
如果代码真的是时间紧迫的,我是否应该费心评估这种静态方法而不是非静态方法?
public struct PixelData
{
public readonly uint raw;
public PixelData(uint raw)
{
this.raw = raw;
}
//JIT inlines this
static bool HasLineOfSight(PixelData p)
{
return (p.raw & 0x8000) != 0;
}
//But what about this?
int GetWeight()
{
return (int)(raw & 0x3FFF);
}
}
MSDN:Static Classes and Static Class Members
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
您可以将 [MethodImpl(MethodImplOptions.AggressiveInlining)]
应用于该方法以尝试强制内联:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int GetWeight()
{
return (int)(raw & 0x3FFF);
}
但是,从 this programmer.se answer 可以看出,内联与非内联实际上差别不大:
Results
struct get property : 0.3097832 seconds
struct inline get property : 0.3079076 seconds
struct method call with params : 1.0925033 seconds
struct inline method call with params : 1.0930666 seconds
struct method call without params : 1.5211852 seconds
struct intline method call without params : 1.2235001 seconds
您最好让编译器自行其是,直到您发现您看到了一些真正的可衡量性能问题。
通过一些研究,我知道下面的静态方法可以使 JIT 内联。但是非静态的也可以内联吗?
如果代码真的是时间紧迫的,我是否应该费心评估这种静态方法而不是非静态方法?
public struct PixelData
{
public readonly uint raw;
public PixelData(uint raw)
{
this.raw = raw;
}
//JIT inlines this
static bool HasLineOfSight(PixelData p)
{
return (p.raw & 0x8000) != 0;
}
//But what about this?
int GetWeight()
{
return (int)(raw & 0x3FFF);
}
}
MSDN:Static Classes and Static Class Members
A call to a static method generates a call instruction in Microsoft intermediate language (MSIL), whereas a call to an instance method generates a callvirt instruction, which also checks for a null object references. However, most of the time the performance difference between the two is not significant.
您可以将 [MethodImpl(MethodImplOptions.AggressiveInlining)]
应用于该方法以尝试强制内联:
[MethodImpl(MethodImplOptions.AggressiveInlining)]
int GetWeight()
{
return (int)(raw & 0x3FFF);
}
但是,从 this programmer.se answer 可以看出,内联与非内联实际上差别不大:
Results
struct get property : 0.3097832 seconds struct inline get property : 0.3079076 seconds struct method call with params : 1.0925033 seconds struct inline method call with params : 1.0930666 seconds struct method call without params : 1.5211852 seconds struct intline method call without params : 1.2235001 seconds
您最好让编译器自行其是,直到您发现您看到了一些真正的可衡量性能问题。