I am developing a component that needs a long type with mutable semantics.
Since .NET does not have volatile long , I created a simple wrapper type that handles read / write access using the Volatile class.
I did not know if I should go with a class or structure, so I decided to check both of them, and I came across very strange behavior.
Here's the test code:
internal class Program { private class VolatileLongClass { private long value; public long Value { get { return Volatile.Read(ref value); } set { Volatile.Write(ref this.value, value); } } } private struct VolatileLongStruct { private long value; public long Value { get { return Volatile.Read(ref value); } set { Volatile.Write(ref this.value, value); } } } private static void Main() { const int iterations = 10; var totalTime = 0L; for (var i = 0; i < iterations; i++) { var watch = Stopwatch.StartNew(); var volatileLong = new VolatileLongClass();
The output I get for VolatileLongStruct:
Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Ms Elapsed = 109 Avg = 109.00
The above conclusion for the structure is consistent. However, the output for VolatileLongClass is:
Ms Elapsed = 17558 <-- *** Ms Elapsed = 105 Ms Elapsed = 105 Ms Elapsed = 105 Ms Elapsed = 105 Ms Elapsed = 105 Ms Elapsed = 17541 <-- *** Ms Elapsed = 105 Ms Elapsed = 105 Ms Elapsed = 105 Avg = 3,593.90
As you can see, there is a significant time difference for some iterations. The exact iteration (s) that takes an abnormal time varies a bit, but there is a constant problem with at least one of the iterations.
Can someone shed some light on the question, why would volatile write take (sometimes) more on a class member than on a structure member?
By the way, the above result was obtained using .Net 4.5 and Release build
source share