Skip to content

Commit

Permalink
Undo 54e132b to speed up interface proxy creation (#551)
Browse files Browse the repository at this point in the history
Creating proxies with DynamicProxy is the single most expensive kind
of operation that Moq does. Commit 54e132b changed how proxies for
interface types are generated so that `object` methods on interfaces
could also be intercepted (and thus set up). Unfortunately, this
change also made interface proxy generation twice as costly!

This commit restores the previous method for interface proxy creation,
and at the same time adds an `InterfaceProxy` class to keep `object`
methods interceptable.
  • Loading branch information
stakx authored Dec 11, 2017
1 parent a152192 commit 806e991
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 6 deletions.
11 changes: 5 additions & 6 deletions Source/ProxyFactories/CastleProxyFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@

using Castle.DynamicProxy;

using Moq.Internals;
using Moq.Properties;

#if FEATURE_CAS
Expand Down Expand Up @@ -88,7 +89,7 @@ static CastleProxyFactory()
public CastleProxyFactory()
{
this.delegateInterfaceCache = new Dictionary<Type, Type>();
this.generationOptions = new ProxyGenerationOptions { Hook = new IncludeObjectMethodsHook() };
this.generationOptions = new ProxyGenerationOptions { Hook = new IncludeObjectMethodsHook(), BaseTypeForInterfaceProxy = typeof(InterfaceProxy) };
this.generator = new ProxyGenerator();
}

Expand All @@ -97,11 +98,9 @@ public override object CreateProxy(Type mockType, Moq.IInterceptor interceptor,
{
if (mockType.GetTypeInfo().IsInterface)
{
// Add type to additional interfaces and mock System.Object instead.
// This way it is also possible to mock System.Object methods.
Array.Resize(ref interfaces, interfaces.Length + 1);
interfaces[interfaces.Length - 1] = mockType;
mockType = typeof(object);
// While `CreateClassProxy` could also be used for interface types,
// `CreateInterfaceProxyWithoutTarget` is much faster (about twice as fast):
return generator.CreateInterfaceProxyWithoutTarget(mockType, interfaces, this.generationOptions, new Interceptor(interceptor));
}

try
Expand Down
116 changes: 116 additions & 0 deletions Source/ProxyFactories/InterfaceProxy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
//Copyright (c) 2007. Clarius Consulting, Manas Technology Solutions, InSTEDD
//https://github.com/moq/moq4
//All rights reserved.

//Redistribution and use in source and binary forms,
//with or without modification, are permitted provided
//that the following conditions are met:

// * Redistributions of source code must retain the
// above copyright notice, this list of conditions and
// the following disclaimer.

// * Redistributions in binary form must reproduce
// the above copyright notice, this list of conditions
// and the following disclaimer in the documentation
// and/or other materials provided with the distribution.

// * Neither the name of Clarius Consulting, Manas Technology Solutions or InSTEDD nor the
// names of its contributors may be used to endorse
// or promote products derived from this software
// without specific prior written permission.

//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
//CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
//INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
//MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
//INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
//OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
//SUCH DAMAGE.

//[This is the BSD license, see
// http://www.opensource.org/licenses/bsd-license.php]

using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;

namespace Moq.Internals
{
/// <summary>Do not use. (Moq requires this class so that <see langword="object"/> methods can be set up on interface mocks.)</summary>
// NOTE: This type is actually specific to our DynamicProxy implementation of `ProxyFactory`.
// It is public because it needs to be visible to the framework's types in `Reflection.Emit`.
// Not sure what `[assembly: InternalsVisibleTo(<some framework assembly>)]` would have to look like.
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class InterfaceProxy
{
private static MethodInfo equalsMethod = typeof(object).GetMethod("Equals", BindingFlags.Public | BindingFlags.Instance);
private static MethodInfo getHashCodeMethod = typeof(object).GetMethod("GetHashCode", BindingFlags.Public | BindingFlags.Instance);
private static MethodInfo toStringMethod = typeof(object).GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance);

/// <summary/>
[DebuggerHidden]
public sealed override bool Equals(object obj)
{
// Forward this call to the interceptor, so that `object.Equals` can be set up.
var invocation = new Invocation(equalsMethod, obj);
((IInterceptor)((IMocked)this).Mock).Intercept(invocation);
return (bool)invocation.ReturnValue;
}

/// <summary/>
[DebuggerHidden]
public sealed override int GetHashCode()
{
// Forward this call to the interceptor, so that `object.GetHashCode` can be set up.
var invocation = new Invocation(getHashCodeMethod);
((IInterceptor)((IMocked)this).Mock).Intercept(invocation);
return (int)invocation.ReturnValue;
}

/// <summary/>
[DebuggerHidden]
public sealed override string ToString()
{
// Forward this call to the interceptor, so that `object.ToString` can be set up.
var invocation = new Invocation(toStringMethod);
((IInterceptor)((IMocked)this).Mock).Intercept(invocation);
return (string)invocation.ReturnValue;
}

private sealed class Invocation : Moq.Invocation
{
private static object[] noArguments = new object[0];

private object returnValue;

public Invocation(MethodInfo method, params object[] arguments)
: base(method, arguments)
{
}

public Invocation(MethodInfo method)
: base(method, noArguments)
{
}

public object ReturnValue => this.returnValue;

public override void Return() { }

public override void Return(object value)
{
this.returnValue = value;
}

public override void ReturnBase() { }
}
}
}

0 comments on commit 806e991

Please sign in to comment.