synclock performance

K

Keith Langer

I would like to know why locking on a new object takes significantly
longer than locking on a strongly typed object. All of the posts I've
seen say that it is best to lock on a "new object", but it takes more
than 3x longer than locking on anything other than object. Here's a
test case:

Module Module1

Sub Main()

Dim T As clsTest
Dim i As Integer
Dim D As Date
Const MAX = 10000000
Dim LL As New Object
Dim DTest As Date
Dim T2 As New clsDummy


T = New clsTest
D = Now
For i = 1 To MAX
T.Index += 1
Next
Console.WriteLine("No lock: " & Now.Ticks - D.Ticks)

T = New clsTest
D = Now
For i = 1 To MAX
SyncLock T
T.Index += 1
End SyncLock
Next
Console.WriteLine("Lock on owner: " & Now.Ticks - D.Ticks)

T = New clsTest
D = Now
For i = 1 To MAX
SyncLock LL
T.Index += 1
End SyncLock
Next
Console.WriteLine("Lock on new object: " & Now.Ticks - D.Ticks)


T = New clsTest
D = Now
For i = 1 To MAX
SyncLock T2
T.Index += 1
End SyncLock
Next
Console.WriteLine("Lock on Dummy object: " & Now.Ticks -
D.Ticks)

Console.ReadLine()


End Sub

Class clsDummy

End Class

Class clsTest
Dim m_Index As Integer
Public Property Index() As Integer
Get
Return m_Index
End Get
Set(ByVal Value As Integer)
m_Index += 1
End Set
End Property
End Class



thanks,
Keith
 
M

Mattias Sjögren

Keith,
I would like to know why locking on a new object takes significantly
longer than locking on a strongly typed object.

Because on each iteration there's a call to

Microsoft.VisualBasic.CompilerServices.FlowControl.CheckForSyncLockOnValueType()

which throws an exception if you're trying to lock on a boxed value
type, because that isn't allowed in VB.

All of the posts I've
seen say that it is best to lock on a "new object", but it takes more
than 3x longer than locking on anything other than object.

I bet all those posts used it in more realistic situations though. For
a one time lock, the perf difference hardly matters. I hope you don't
have real code that looks like what you posted.



Mattias
 
K

Keith Langer

Mattias,

Obviously this was just a test case to demonstrate the differences,
and not real code. In light of the performance difference, doesn't it
make more sense to use an empty custom class instead of a generic
object?

Keith
 
M

Mattias Sjögren

Keith,
In light of the performance difference, doesn't it
make more sense to use an empty custom class instead of a generic
object?

Personally I wouldn't bother. At least not unless the code was in a
tight loop or something and profiling the code showed that it was a
bottleneck and needed some extra perf boost.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top