简体   繁体   中英

Any performance issue using static function Objects

I have a piece of code like this. I write this because I love extension methods and lambda expression:

public static class TuneingRules
{
    public static Func<HtmlNode, bool> IsNodeHavingClearNone = (node) =>
    {
        if (node.HasAttributes)
        {
            // HtmlAttribute atr = item.Attributes.Where(at => at.Name == "id" && at.Value == "hello").FirstOrDefault();
            HtmlAttribute atr = node.Attributes.Where(at => at.Name == "style").FirstOrDefault();
            if (atr != null)
            {
                return Regex.Match(atr.Value, "clear\\s*:\\s*none;").Success;
            }
        }
        return true;
    };

}

and extension method like this.

public static class ExtensionMethods
{
      #region Ignoring Rules
      public static bool Ignore(this HtmlNode Node, Func<HtmlNode,bool> func) {
          return func(Node);
      }
      #endregion 
}

now I have two approaches to use this piece of code..

1 case

if (!htmlNode.Ignore(TuneingRules.IsNodeHavingClearNone)){
   //then do somethings
}
 // here i am open to write lambda expression like this.
if (!htmlNode.Ignore( node =>  node.innerText =="" ){
   //then do somethings
}

2 case

if (!TuneingRules.IsNodeHavingClearNone(htmlNode)) { 
     //then do something                      
}

I'm afraid that there are any performance issues if TuneingRules has many static Func<HtmlNode,bool> objects. Do i need to refactor my code? In the first case there is an extra call going through ignore function... but in the second case i can call the function object directly. Or is there another way to write this code in order to stick with lambda as well as extension methods?

No, there is no performance issue.

There will be a small performance hit the first time that you use the TuneingRules class, as the static constructor will be called and initialise all the static variables. That should however be quite small compared to the actual work that the function does.

Likewise, doing one extra method call is negligible compared to the work that the function does. It's even possible that the extension method call will be inlined by the JIT compiler, so that the executed code will actually do the same thing as in your second case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM