Skip to content
This repository has been archived by the owner on Jun 22, 2023. It is now read-only.

Improved performance of the Instance property #39

Merged
merged 4 commits into from
Apr 28, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 43 additions & 66 deletions src/GeoAPI/GeometryServiceProvider.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

namespace GeoAPI
{
Expand All @@ -9,90 +9,67 @@ namespace GeoAPI
/// </summary>
public static class GeometryServiceProvider
{
private static IGeometryServices _instance;
private static readonly object LockObject = new object();
private static volatile IGeometryServices _instance;
Copy link
Member

Choose a reason for hiding this comment

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

Foreword: I haven't actually thought this through completely.

I don't actually think we need this to be volatile, and if we think that this property is going to be "hot", then we actually don't really want it to be volatile. Every other read/write of this field occurs immediately after a Monitor.Enter call, which triggers a full memory barrier itself, so the volatile semantics seem to only affect the hot path.

So it seems to me that the worst that can happen without volatile is that every CPU comes in here with a stale cache and observes an uninitialized value, then they all hit the lock, then one of them initializes it properly (slow), then every other CPU sees the value from the other thread one-by-one (fast), then for the rest of the application every access is as fast as it can possibly be.

It seems like that's also the worst-case for volatile, except that at the end, every access for the rest of the application still has to go through a partial memory barrier. I don't actually see a window where volatile helps at all, compared to no volatile...

private static readonly object _lock = new object();

/// <summary>
/// Gets or sets the <see cref="IGeometryServices"/> instance.
/// </summary>
public static IGeometryServices Instance
{
get
{
lock (LockObject)
{
return _instance ?? (_instance = ReflectInstance());
}
}

get => _instance ?? InitializeInstance();
set
{
if (value == null)
throw new ArgumentNullException("value", "You must not assign null to Instance!");

lock (LockObject)
{
throw new ArgumentNullException(nameof(value));
lock (_lock)
_instance = value;
}
}
}

#if HAS_SYSTEM_REFLECTION_ASSEMBLY_GETEXPORTEDTYPES
private static IEnumerable<Type> GetLoadableTypes(Assembly assembly)
private static IGeometryServices InitializeInstance()
{
if (assembly == null)
return new Type[0];

try
{
return assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException ex)
{
var types = ex.Types;
IList<Type> list = new List<Type>(types.Length);
foreach (var t in types)
if (t != null && t.IsPublic)
{
list.Add(t);
}
return list;
}
catch
#if COMPAT_BOOTSTRAP_USING_REFLECTION && HAS_SYSTEM_APPDOMAIN_GETASSEMBLIES && HAS_SYSTEM_REFLECTION_ASSEMBLY_GETEXPORTEDTYPES
lock (_lock)
{
return new Type[0];
}
}
#else
private static IEnumerable<Type> GetLoadableTypes(Assembly assembly)
{
throw new NotSupportedException("The compact framework does not support retrieve exported types from assembly");
}
#endif
var instance = _instance;
if (instance != null) return instance;
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
if (assembly.GlobalAssemblyCache && assembly.CodeBase == Assembly.GetExecutingAssembly().CodeBase)
continue;

private static IGeometryServices ReflectInstance()
{
#if COMPAT_BOOTSTRAP_USING_REFLECTION && HAS_SYSTEM_APPDOMAIN_GETASSEMBLIES
var a = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in a)
{
// Take a look at issue 114: http://code.google.com/p/nettopologysuite/issues/detail?id=114
if (assembly is System.Reflection.Emit.AssemblyBuilder) continue;
if (assembly.GetType().FullName == "System.Reflection.Emit.InternalAssemblyBuilder") continue;
if (assembly.GlobalAssemblyCache && assembly.CodeBase == Assembly.GetExecutingAssembly().CodeBase) continue;
var assemblyType = assembly.GetType();
if (assemblyType == typeof(AssemblyBuilder) ||
assemblyType.FullName == "System.Reflection.Emit.InternalAssemblyBuilder")
continue;

foreach (var t in GetLoadableTypes(assembly))
{
if (t.IsInterface) continue;
if (t.IsAbstract) continue;
if (t.IsNotPublic) continue;
if (!typeof(IGeometryServices).IsAssignableFrom(t)) continue;
Type[] types;

var constuctors = t.GetConstructors();
foreach (var constructorInfo in constuctors)
try
{
if (constructorInfo.IsPublic && constructorInfo.GetParameters().Length == 0)
return (IGeometryServices)Activator.CreateInstance(t);
types = assembly.GetExportedTypes();
}
catch (ReflectionTypeLoadException ex)
{
types = ex.Types;
}
catch (Exception)
{
continue;
}

var requiredType = typeof(IGeometryServices);
foreach (var type in types)
{
if (type.IsNotPublic || type.IsInterface || type.IsAbstract || !requiredType.IsAssignableFrom(type))
continue;

foreach (var constructor in type.GetConstructors())
{
if (constructor.IsPublic && constructor.GetParameters().Length == 0)
return _instance = instance = (IGeometryServices)Activator.CreateInstance(type);
Copy link
Member

Choose a reason for hiding this comment

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

no need for the = instance part of this

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, fixed.

}
}
}
}
Expand Down