Skip to content

Improving specification evaluation performance #182

Description

@devbased

I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
I need to know, should i continue and do the same for other expressions or not?

Long story short, here's the code and benchmark results

publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
[MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
.NET SDK=6.0.100
[Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT

Before

MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

After

MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      , 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
       blocks
      (function() {
      function addCopyButtons() {
      document.querySelectorAll('pre code').forEach(function(codeBlock) {
      if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
      codeBlock.parentElement.setAttribute('data-copy-added', 'true');
      var btn = document.createElement('button');
      btn.textContent = 'Copy';
      btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
      btn.onmouseover = function() { this.style.opacity = '1'; };
      btn.onmouseout = function() { this.style.opacity = '0.7'; };
      btn.onclick = function() {
      navigator.clipboard.writeText(codeBlock.textContent).then(function() {
      btn.textContent = 'Copied!';
      setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
      });
      };
      codeBlock.parentElement.style.position = 'relative';
      codeBlock.parentElement.appendChild(btn);
      });
      }
      addCopyButtons();
      // Re-run on dynamic content
      var observer = new MutationObserver(addCopyButtons);
      observer.observe(document.body, { childList: true, subtree: true });
      })();
      }
      } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
      })();
      (function(){
      try {
      var __m = "github.com";
      var __re = new RegExp('^' + "github\\.com" + '
      Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
      Skip to content

      Improving specification evaluation performance #182

      Description

      @devbased

      I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
      So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
      With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

      I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
      I need to know, should i continue and do the same for other expressions or not?

      Long story short, here's the code and benchmark results

      publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
      [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
      BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
      Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
      .NET SDK=6.0.100
      [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
      DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
      

      Before

      MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
      InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
      InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
      InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
      InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

      After

      MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
      InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
      InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
      InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
      InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
      InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
      InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
      InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
      InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

      Metadata

      Metadata

      Assignees

      No one assigned

        Labels

        No labels
        No labels

        Projects

        No projects

          Milestone

          Relationships

          None yet

          Development

          No branches or pull requests

          Issue actions

          , 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
          Skip to content

          Improving specification evaluation performance #182

          Description

          @devbased

          I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
          So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
          With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

          I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
          I need to know, should i continue and do the same for other expressions or not?

          Long story short, here's the code and benchmark results

          publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
          [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
          BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
          Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
          .NET SDK=6.0.100
          [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
          DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
          

          Before

          MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
          InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
          InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
          InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
          InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

          After

          MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
          InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
          InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
          InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
          InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
          InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
          InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
          InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
          InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

          Metadata

          Metadata

          Assignees

          No one assigned

            Labels

            No labels
            No labels

            Projects

            No projects

              Milestone

              Relationships

              None yet

              Development

              No branches or pull requests

              Issue actions

              , 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
              Skip to content

              Improving specification evaluation performance #182

              Description

              @devbased

              I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
              So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
              With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

              I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
              I need to know, should i continue and do the same for other expressions or not?

              Long story short, here's the code and benchmark results

              publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
              [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
              BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
              Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
              .NET SDK=6.0.100
              [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
              DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
              

              Before

              MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
              InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
              InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
              InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
              InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

              After

              MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
              InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
              InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
              InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
              InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
              InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
              InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
              InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
              InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

              Metadata

              Metadata

              Assignees

              No one assigned

                Labels

                No labels
                No labels

                Projects

                No projects

                  Milestone

                  Relationships

                  None yet

                  Development

                  No branches or pull requests

                  Issue actions

                  , 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
                  Skip to content

                  Improving specification evaluation performance #182

                  Description

                  @devbased

                  I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
                  So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
                  With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

                  I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
                  I need to know, should i continue and do the same for other expressions or not?

                  Long story short, here's the code and benchmark results

                  publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
                  [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
                  BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
                  Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
                  .NET SDK=6.0.100
                  [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                  DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                  

                  Before

                  MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
                  InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
                  InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
                  InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
                  InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

                  After

                  MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
                  InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
                  InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
                  InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
                  InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
                  InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
                  InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
                  InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
                  InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

                  Metadata

                  Metadata

                  Assignees

                  No one assigned

                    Labels

                    No labels
                    No labels

                    Projects

                    No projects

                      Milestone

                      Relationships

                      None yet

                      Development

                      No branches or pull requests

                      Issue actions

                      , 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
                      Skip to content

                      Improving specification evaluation performance #182

                      Description

                      @devbased

                      I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
                      So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
                      With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

                      I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
                      I need to know, should i continue and do the same for other expressions or not?

                      Long story short, here's the code and benchmark results

                      publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
                      [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
                      BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
                      Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
                      .NET SDK=6.0.100
                      [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                      DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                      

                      Before

                      MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
                      InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
                      InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
                      InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
                      InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

                      After

                      MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
                      InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
                      InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
                      InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
                      InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
                      InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
                      InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
                      InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
                      InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

                      Metadata

                      Metadata

                      Assignees

                      No one assigned

                        Labels

                        No labels
                        No labels

                        Projects

                        No projects

                          Milestone

                          Relationships

                          None yet

                          Development

                          No branches or pull requests

                          Issue actions

                          , 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
                          Skip to content

                          Improving specification evaluation performance #182

                          Description

                          @devbased

                          I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
                          So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
                          With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

                          I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
                          I need to know, should i continue and do the same for other expressions or not?

                          Long story short, here's the code and benchmark results

                          publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
                          [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
                          BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
                          Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
                          .NET SDK=6.0.100
                          [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                          DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                          

                          Before

                          MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
                          InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
                          InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
                          InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
                          InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

                          After

                          MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
                          InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
                          InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
                          InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
                          InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
                          InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
                          InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
                          InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
                          InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

                          Metadata

                          Metadata

                          Assignees

                          No one assigned

                            Labels

                            No labels
                            No labels

                            Projects

                            No projects

                              Milestone

                              Relationships

                              None yet

                              Development

                              No branches or pull requests

                              Issue actions

                              , 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); Improving specification evaluation performance · Issue #182 · ardalis/Specification · GitHub
                              Skip to content

                              Improving specification evaluation performance #182

                              Description

                              @devbased

                              I don't like current spec evaluation because it compiles expressions with every call to Evaluate.
                              So i have added benchmark project to provide ability to measure performance and replaced IEnumerable<(Expression<Func<T, string>>, string, int)> ISpecification{T}.SearchCriterias with IEnumerable<SearchExpressionBase<T>>. There also 2 approaches to compile expressions: one is default dotnet compile and second is CompileFast from dadhi/FastExpressionCompiler.
                              With this changes user code could cache specifications to not just reduce amount of allocations but also to avoid recompilation.

                              I'm not sure if it's super precise benchmark since i don't have enough experience in such things and i've ran it on my home PC, however everyone can do it by himself to verify results.
                              I need to know, should i continue and do the same for other expressions or not?

                              Long story short, here's the code and benchmark results

                              publicinterfaceISpecification<T>{// other members omitted for brevityIEnumerable<SearchExpressionBase<T>>SearchCriterias{get;}}publicabstractclassSearchExpressionBase<T>{protectedSearchExpressionBase(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1){this.Source=source;this.SearchTerm=searchTerm;this.SearchGroup=searchGroup;}publicExpression<Func<T,string>>Source{get;}publicstringSearchTerm{get;}publicintSearchGroup{get;}publicabstractFunc<T,string>SourceFunc{get;}}publicsealedclassSearchExpression<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpression(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(this.Source.Compile);}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicsealedclassSearchExpressionFast<T>:SearchExpressionBase<T>{privatereadonlyLazy<Func<T,string>>sourceFuncLazy;publicSearchExpressionFast(Expression<Func<T,string>>source,stringsearchTerm,intsearchGroup=1):base(source,searchTerm,searchGroup){this.sourceFuncLazy=newLazy<Func<T,string>>(()=>this.Source.CompileFast());}publicoverrideFunc<T,string>SourceFunc=>this.sourceFuncLazy.Value;}publicstaticISpecificationBuilder<T>Search<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpression<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicstaticISpecificationBuilder<T>SearchFast<T>(thisISpecificationBuilder<T>specificationBuilder,Expression<Func<T,string>>selector,stringsearchTerm,intsearchGroup=1)whereT:class{((List<SearchExpressionBase<T>>)specificationBuilder.Specification.SearchCriterias).Add(newSearchExpressionFast<T>(selector,searchTerm,searchGroup));returnspecificationBuilder;}publicclassSearchEvaluator:IInMemoryEvaluator{privateSearchEvaluator(){}publicstaticSearchEvaluatorInstance{get;}=newSearchEvaluator();publicIEnumerable<T>Evaluate<T>(IEnumerable<T>query,ISpecification<T>specification){foreach(varsearchGroupinspecification.SearchCriterias.GroupBy(x =>x.SearchGroup)){varcriterias=searchGroup.Select(x =>(x.SourceFunc,x.SearchTerm));query=query.Where(x =>criterias.Any(c =>c.SourceFunc(x).Like(c.SearchTerm)));}returnquery;}}
                              [MemoryDiagnoser,MedianColumn,RankColumn,CsvExporter]publicclassInMemorySearchEvaluatorBenchmark{privateSearchEvaluatorevaluator;privateConsumerconsumer;privateIEnumerable<string>data;privateTestSpecificationspecification;privateTestSpecificationFastspecificationFast;[Params(1,10,100,1000)]publicintRepeatCount;[GlobalSetup]publicvoidGlobalSetup(){this.evaluator=SearchEvaluator.Instance;this.data=Enumerable.Range(1,247).Select(x =>$"Test {x%124} data.");this.specification=newTestSpecification();this.specificationFast=newTestSpecificationFast();this.consumer=newConsumer();}[Benchmark]publicvoidInMemorySearchEvaluator_Evaluate(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specification).Consume(this.consumer);}}[Benchmark]publicvoidInMemorySearchEvaluator_EvaluateFast(){for(vari=0;i<this.RepeatCount;++i){this.evaluator.Evaluate(this.data,this.specificationFast).Consume(this.consumer);}}privatesealedclassTestSpecification:Specification<string>{publicTestSpecification(){this.Query.Search(x =>x,"%123%");}}privatesealedclassTestSpecificationFast:Specification<string>{publicTestSpecificationFast(){this.Query.SearchFast(x =>x,"%123%");}}}
                              BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19042.1165 (20H2/October2020Update)
                              Intel Core i5-9600K CPU 3.70GHz (Coffee Lake), 1 CPU, 6 logical and 6 physical cores
                              .NET SDK=6.0.100
                              [Host] : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                              DefaultJob : .NET 6.0.0 (6.0.21.52210), X64 RyuJIT
                              

                              Before

                              MethodRepeatCountMeanErrorStdDevMedianRankGen 0Gen 1Gen 2Allocated
                              InMemorySearchEvaluator_Evaluate17.258 ms0.1064 ms0.0943 ms7.246 ms1226.5625109.37507.81251 MB
                              InMemorySearchEvaluator_Evaluate1072.422 ms1.0351 ms0.9175 ms72.293 ms22285.71431142.8571-10 MB
                              InMemorySearchEvaluator_Evaluate100738.127 ms14.2779 ms16.9969 ms732.809 ms323000.000011000.0000-105 MB
                              InMemorySearchEvaluator_Evaluate10007,304.372 ms69.1068 ms64.6425 ms7,320.962 ms4234000.0000117000.000010000.00001,049 MB

                              After

                              MethodRepeatCountMeanErrorStdDevMedianRankGen 0Allocated
                              InMemorySearchEvaluator_Evaluate1104.2 μs0.92 μs0.77 μs103.7 μs114.404367 KB
                              InMemorySearchEvaluator_EvaluateFast1103.8 μs0.51 μs0.48 μs103.7 μs114.404367 KB
                              InMemorySearchEvaluator_Evaluate101,015.9 μs12.42 μs11.62 μs1,016.4 μs2144.5313665 KB
                              InMemorySearchEvaluator_EvaluateFast101,035.8 μs16.52 μs15.45 μs1,037.6 μs3144.5313665 KB
                              InMemorySearchEvaluator_Evaluate10010,844.6 μs215.23 μs376.97 μs10,984.3 μs51437.50006,651 KB
                              InMemorySearchEvaluator_EvaluateFast10010,265.1 μs121.38 μs113.54 μs10,246.4 μs41437.50006,651 KB
                              InMemorySearchEvaluator_Evaluate1000103,440.0 μs1,181.59 μs1,105.26 μs103,007.3 μs614400.000066,509 KB
                              InMemorySearchEvaluator_EvaluateFast1000110,561.6 μs840.64 μs786.33 μs110,465.3 μs714400.000066,509 KB

                              Metadata

                              Metadata

                              Assignees

                              No one assigned

                                Labels

                                No labels
                                No labels

                                Projects

                                No projects

                                  Milestone

                                  Relationships

                                  None yet

                                  Development

                                  No branches or pull requests

                                  Issue actions