如何解决通用工厂:缓存与重复实例化
| 我有一个通用工厂,该工厂在实例返回之前会缓存它(简化代码):static class Factory<T>
where T : class
{
private static T instance;
public static T GetInstance()
{
if (instance == null) instance = new T();
return instance;
}
}
我想用非缓存方法代替这种方法,以表明缓存对实例化性能没有意义(我相信创建新对象非常便宜)。
因此,我想编写一个负载测试,它将创建一个动态的,仅限运行时的类型(例如1000)的交易并将其加载到我的工厂中。一个会缓存,另一个会缓存。
解决方法
在我看来,您的同事希望进行过早的优化。缓存对象很少是一个好主意。实例化很便宜,而且我只会在证明它会更快的地方缓存对象。高性能套接字服务器就是这种情况。
但是要回答您的问题:缓存对象将总是更快。将它们保持在“ 1”或类似的值将使开销保持很小,并且随着对象数量的增加,性能不应降低。
因此,如果您愿意接受更大的内存消耗和更高的复杂性,请使用缓存。
,这是我的两分钱,尽管我同意jgauffin和Daniel Hilgarth的回答。以这种方式使用静态成员使用泛型类型缓存将直观地为每个要缓存的类型创建其他并行类型,但是了解这对于引用类型和值类型如何不同的工作很重要。对于作为T的引用类型,所产生的其他泛型类型使用的资源应比值类型的等效用法少。
那么什么时候应该使用泛型类型技术来生成缓存呢?以下是我使用的一些重要标准。
1.您想允许缓存每个感兴趣的类的单个实例。
2.您想使用编译时通用类型约束来对高速缓存中使用的类型强制执行规则。使用类型约束,您可以强制需要实例来实现多个接口,而不必为这些类定义基本类型。
3.在AppDomain的生存期内,您无需从缓存中删除项目。
顺便说一下,一个可能对搜索有用的术语是“代码爆炸”,它是一种通用术语,用于定义需要大量代码来执行某些定期发生的任务并且通常线性增长或恶化的情况。项目需求的增长。在泛型类型方面,我听说过并且通常会使用术语“类型爆炸”来描述类型的泛滥,因为您开始合并和组成几种泛型类型。
另一个重要的一点是,在这些情况下,工厂和缓存始终可以分开,并且在大多数情况下,可以为它们提供相同的接口,该接口将允许您替换工厂(每个调用一个新实例)或实质上包装工厂的缓存并根据情况(例如,类型爆炸问题)使用同一接口进行委托。您的缓存也可能承担更多的责任,例如更复杂的缓存策略,其中特定类型的缓存可能有所不同(例如引用类型与值类型)。如果您对此感到好奇,那么诀窍就是定义将类进行缓存的泛型类作为实现工厂接口的实际具体类型中的私有类。如果您愿意,我可以举个例子。
根据要求更新示例代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace CacheAndFactory
{
class Program
{
private static int _iterations = 1000;
static void Main(string[] args)
{
var factory = new ServiceFactory();
// Exercise the factory which implements IServiceSource
AccessAbcTwoTimesEach(factory);
// Exercise the generics cache which also implements IServiceSource
var cache1 = new GenericTypeServiceCache(factory);
AccessAbcTwoTimesEach(cache1);
// Exercise the collection based cache which also implements IServiceSource
var cache2 = new CollectionBasedServiceCache(factory);
AccessAbcTwoTimesEach(cache2);
Console.WriteLine(\"Press any key to continue\");
Console.ReadKey();
}
public static void AccessAbcTwoTimesEach(IServiceSource source)
{
Console.WriteLine(\"Excercise \" + source.GetType().Name);
Console.WriteLine(\"1st pass - Get an instance of A,B,and C through the source and access the DoSomething for each.\");
source.GetService<A>().DoSomething();
source.GetService<B>().DoSomething();
source.GetService<C>().DoSomething();
Console.WriteLine();
Console.WriteLine(\"2nd pass - Get an instance of A,and C through the source and access the DoSomething for each.\");
source.GetService<A>().DoSomething();
source.GetService<B>().DoSomething();
source.GetService<C>().DoSomething();
Console.WriteLine();
var clock = Stopwatch.StartNew();
for (int i = 0; i < _iterations; i++)
{
source.GetService<A>();
source.GetService<B>();
source.GetService<C>();
}
clock.Stop();
Console.WriteLine(\"Accessed A,and C \" + _iterations + \" times each in \" + clock.ElapsedMilliseconds + \"ms through \" + source.GetType().Name + \".\");
Console.WriteLine();
Console.WriteLine();
}
}
public interface IService
{
}
class A : IService
{
public void DoSomething() { Console.WriteLine(\"A.DoSomething(),HashCode: \" + this.GetHashCode()); }
}
class B : IService
{
public void DoSomething() { Console.WriteLine(\"B.DoSomething(),HashCode: \" + this.GetHashCode()); }
}
class C : IService
{
public void DoSomething() { Console.WriteLine(\"C.DoSomething(),HashCode: \" + this.GetHashCode()); }
}
public interface IServiceSource
{
T GetService<T>()
where T : IService,new();
}
public class ServiceFactory : IServiceSource
{
public T GetService<T>()
where T : IService,new()
{
// I\'m using Activator here just as an example
return Activator.CreateInstance<T>();
}
}
public class GenericTypeServiceCache : IServiceSource
{
IServiceSource _source;
public GenericTypeServiceCache(IServiceSource source)
{
_source = source;
}
public T GetService<T>()
where T : IService,new()
{
var serviceInstance = GenericCache<T>.Instance;
if (serviceInstance == null)
{
serviceInstance = _source.GetService<T>();
GenericCache<T>.Instance = serviceInstance;
}
return serviceInstance;
}
// NOTE: This technique will cause all service instances cached here
// to be shared amongst all instances of GenericTypeServiceCache which
// may not be desireable in all applications while in others it may
// be a performance enhancement.
private class GenericCache<T>
{
public static T Instance;
}
}
public class CollectionBasedServiceCache : IServiceSource
{
private Dictionary<Type,IService> _serviceDictionary;
IServiceSource _source;
public CollectionBasedServiceCache(IServiceSource source)
{
_serviceDictionary = new Dictionary<Type,IService>();
_source = source;
}
public T GetService<T>()
where T : IService,new()
{
IService serviceInstance;
if (!_serviceDictionary.TryGetValue(typeof(T),out serviceInstance))
{
serviceInstance = _source.GetService<T>();
_serviceDictionary.Add(typeof(T),serviceInstance);
}
return (T)serviceInstance;
}
private class GenericCache<T>
{
public static T Instance;
}
}
}
概括地说,上面的代码是一个控制台应用程序,具有用于提供服务源抽象的接口的概念。我使用IService通用约束只是为了展示它可能如何起作用的示例。我不想键入或发布1000个单独的类型定义,所以我做了第二件好事,并创建了三个类-A,B和C-并使用每种技术每1000次访问了它们-重复实例化,泛型类型缓存,和基于集合的缓存。
通过少量访问,差异可以忽略不计,但是我的服务构造函数当然是简单的(默认的无参数构造函数),因此它不计算任何内容,访问数据库,访问配置或典型服务类在构造它们时所做的任何事情。如果不是这种情况,那么某种缓存策略的好处显然将对性能有所帮助。同样,即使在具有1,000,000次访问的caes中访问默认构造函数时,未缓存和未缓存之间也存在巨大差异(3s:120ms),因此,教训是,如果您要进行大量访问或需要频繁访问的复杂计算在整个工厂中进行缓存不仅有益,而且取决于是否会影响用户的感知或对时间敏感的业务流程,因此缓存是否必要,否则所带来的好处可忽略不计。要记住的重要一点是,您不仅要担心实例化时间,而且还要担心垃圾收集器上的负载。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。