Skip to content
This repository was archived by the owner on Nov 13, 2026. It is now read-only.

Monitor.GetLock: No dynamic type checks if IsLock == true - #1288

Merged
jkotas merged 1 commit into
dotnet:masterfrom
jamesqo:patch-2
May 17, 2016
Merged

jkotas merged 1 commit into
dotnet:masterfrom
jamesqo:patch-2

Conversation

@jamesqo

@jamesqo jamesqo commented May 17, 2016

Copy link
Copy Markdown
Contributor

Monitor.GetLock uses Lock.IsLock to determine whether a given object is a Lock. The Lock.IsLock function is optimized to avoid "the overhead of the full casting logic in the runtime," yet we still perform a typecheck when we cast to Lock since the compiler doesn't know that obj must be an instance of Lock at that point.

This change changes it to use RuntimeHelpers.UncheckedCast instead of a regular cast to avoid the overhead of dynamic typechecking.

Public methods this affects (if obj is a Lock):

  • Enter
  • TryEnter
  • Exit
  • IsEntered

cc @jkotas

@jkotas

jkotas commented May 17, 2016

Copy link
Copy Markdown
Member

LGTM. Thanks!

@jkotas
jkotas merged commit 07a0400 into dotnet:master May 17, 2016
@jamesqo
jamesqo deleted the patch-2 branch May 17, 2016 06:19

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be better to have Lock.AsLock(obj) in the Lock class so that both the logic of IsLock and AsLock is optimized without moving that knowledge wherever this is needed?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or maybe not have Lock.IsLock at all and just inline it here?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure what you mean. `obj' could be something else than Lock, no?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant that Lock.IsLock method can be deleted and the code here changed to:

        ... comment here...
        if (obj.EETypePtr == EETypePtr.EETypePtrOf<Lock>())
            return RuntimeHelpers.UncheckedCast<Lock>(obj);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@jamesqo jamesqo May 19, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds ok, I'll submit a PR for that soon (edit: already done in #1311)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants