Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c# - Actual Performance of Fields vs. Properties

I'm doing some post-build CIL weaving that adds CIL to all methods in an assembly (in other words tons of methods). Each method checks if a specific value is null. Example (C# Reflector'd version of CIL code):

// CIL woven region start
if (MyType.Something == null) {
 // ... some new stuff
}
// CIL woven region end

What is the performance impact of having MyType.Something as a Property vs. a Field? I know I've read that the C# compiler performs special optimizations and there should be no performance impact in that case...but what about in the case of direct CIL code (no C# compiler)...? Or is it the JIT compiler that allows for these optimizations (so direct CIL code still benefits)?

Will emitting OpCode.Call for the static property's accessor have poorer performance than Ldsfld (bear in mind this is across tens of thousands of invocations since every method in the assembly is woven)?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When developing the math library for SlimDX, we found that, on pre-.NET 3.5 SP1 frameworks, using fields for the members of the math types (such as X, Y, Z for a Vector3) gave a disproportionate performance increase over properties. In other words, the difference was noticeable for small math functions which heavily accessed properties.

This has since been improved since .NET 3.5 SP1 (see JIT inling). While I believe that the JIT prior to that will still inline small methods (properties are simply methods after all), there is a bug in the earlier frameworks that prevented inlining of methods that take or return value types.

Note that the difference, when there, is still quite small. I would still elect to use properties in all but the most performance critical cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...