通用工厂:缓存与重复实例化

如何解决通用工厂:缓存与重复实例化

| 我有一个通用工厂,该工厂在实例返回之前会缓存它(简化代码):
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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-