delegate vs condition check

hello everyone,

today i tested the speed of a delegate relaying to a function against
the speed of an an if, that checks the condition of a boolean value,
relaying to a function (the code is attached at the end of this post).
in my test it turned out, the delegate was twice as fast as checking
the boolean.

this lead me to the conclusion, that whenever object behavior depends
on values, known from time of construction, it is faster to compose an
object (compose of delegates and/or other objects) at construction
time, rather than checking condition(s) every time an object is used.
this goes with the constraint, that cost of construction by
composition must be smaller than the summarized cost of using the
object over its lifetime (cost of construction by composition must be
reasonable low).

does everyone concure? do i miss something?


regards,
arthur




 here is the code:

    public abstract class BaseClass
    {
        protected bool _Value;
        public BaseClass(bool Value)
        {
            _Value=Value;
            this.Initialize();
        }
        protected abstract void Initialize();
        public abstract void Action();
        protected void Action1() { }
        protected void Action2() { }
    }

    public class DelegateClass : BaseClass
    {
        public DelegateClass(bool Value) : base(Value) { }
        private DoDelegate _DoAction = null;
        protected override void Initialize()
        {
            if (_Value)
                _DoAction = new DoDelegate(this.Action1);
            else
                _DoAction = new DoDelegate(this.Action2);
        }
        public override void Action()
        {
            _DoAction();
        }
        private delegate void DoDelegate();
    }

    public class ConditionClass : BaseClass
    {
        public ConditionClass(bool Value) : base(Value) { }
        protected override void Initialize()
        {
        }
        public override void Action()
        {
            if (_Value)
                this.Action1();
            else
                this.Action2();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int iterations = 100000000;
            Console.WriteLine(iterations);
            bool value = true;
            Console.WriteLine(value);

            BaseClass action = new DelegateClass(value);
            TimeSpan duration = Iterate(iterations, action);
            Console.WriteLine("Delegate: "+duration);

            action = new ConditionClass(value);
            duration = Iterate(iterations, action);
            Console.WriteLine("Condition: "+duration);

            Console.WriteLine("Press ENTER to exit.");
            Console.ReadLine();
        }

        private static TimeSpan Iterate(int iterations, BaseClass
action)
        {
            DateTime start = DateTime.Now;
            for (int i = 0; i < iterations; i++)
            {
                action.Action();
            }
            DateTime end = DateTime.Now;
            TimeSpan duration = end.Subtract(start);
            return duration;
        }
    }
0
Art
6/29/2010 3:05:14 PM
dotnet.languages.csharp 1931 articles. 0 followers. Follow

1 Replies
646 Views

Similar Articles

[PageSpeed] 44

Art wrote:
> hello everyone,
> 
> today i tested the speed of a delegate relaying to a function against
> the speed of an an if, that checks the condition of a boolean value,
> relaying to a function (the code is attached at the end of this post).
> in my test it turned out, the delegate was twice as fast as checking
> the boolean.
> 
> this lead me to the conclusion, that whenever object behavior depends
> on values, known from time of construction, it is faster to compose an
> object (compose of delegates and/or other objects) at construction
> time, rather than checking condition(s) every time an object is used.
> this goes with the constraint, that cost of construction by
> composition must be smaller than the summarized cost of using the
> object over its lifetime (cost of construction by composition must be
> reasonable low).
> 
> does everyone concure? do i miss something?

One big issue with your benchmark code is that it does no "warm-up" 
iterations to attempt to get things into a stable state (JIT compiled, 
cache lines set, CPU pipelines filled including pre-fetch and branch 
prediction, etc.).  You also do only one trial per execution of the 
program, rather than doing several and averaging the results after 
discarding the outliers.  So your observations may or may not be accurate.

That said, while I haven't tried the test myself, I see no obvious 
reason that a delegate invocation _wouldn't_ be faster, since it's an 
invariant condition while the boolean test is not (or at least, there's 
no way for the compiler or CPU to know that it's not).  And it stands to 
reason that invariant conditions can be cached/predicted/etc. better 
than variant conditions.

But, your analysis overlooks a few very important points:

   � The difference in speed (if any) might be accounted for by 
optimizations that the JIT compiler or even CPU is able to make in your 
benchmark code, but which would not apply in a more complicated 
scenario.  The only true way to know for sure whether an optimization 
will help is to test it in production code.

   � Delegates cost memory, and use of memory can slow a program down. 
So whether this approach nets a benefit will depend heavily on how many 
delegates the approach winds up creating.  Doing it in a static class or 
in an instance of a class that is created only once or a few times won't 
change the outcome, but doing it in a class that is instantiated  large 
number of times could produce a significant increase in memory usage, 
which can disturb locality or even cause increased swap file usage, both 
of which will _dramatically_ slow the program down.

   � Whatever the difference in performance cost, it is highly unlikely 
that it is significant when compared to the cost of the code being 
controlled by the condition.  Your benchmark is pretty much a worst-case 
scenario, because the methods being called do nothing at all.  A method 
that does even something as simple as checking a boolean flag will 
automatically take at least as long as the dispatch mechanism itself, 
and of course most methods do things far more interesting than that.

I would expect in the typical case that the cost of dispatch winds up 
being less than 10% of the total cost of calling the method, perhaps 
even less than 1%, and of course that difference in cost is further 
reduced in significant when the cost of the one method being dispatched 
is considered in context of the entire program.  Even if that method 
accounts for 10% of the execution time of the program (which would be 
very unusual), that means that the net effect on program execution time 
would be less than 1% even under the generous assumption that the 
dispatching difference can account for a 10% improvement in method 
invocation time.

In other words, even if this is a valid observation, it's unlikely to 
have any practical effect since the performance improvement is not large 
enough to outweigh the question of which version is more maintainable. 
Either _could_ be the more maintainable approach, depending on context, 
and _that_ is the question that should drive the implementation here, 
not the performance considerations.

Pete
0
Peter
6/29/2010 3:23:36 PM
Reply:

Similar Artilces:

Business Assets vs. Home Inventory...???
Should I create Asset Accounts for my business assets like computer equipment, machinery, etc? Or should I just include those things with my Home Inventory? So far I'm able to expense my assets (Section 179) so I haven't had to worry about tracking business asset depreciation and things like that, but I'd like to know how to handle it for future reference. Any information would be greatly appreciated. Thanks! "DRUAngell" <DRUAngell@discussions.microsoft.com> wrote in message news:F1A4328C-8DBB-49BC-ABD3-82204E06E580@microsoft.com... > Should I create As...

Delegate folder
I have set a user up so they can view another user's inbox, calendar etc, but wish to allow the delegate access to the other users folder via the Folder List, rather than them having to go to File, Open, Other User's Folder. How can I do this? ...

conditional formatting #75
i would like to shade every other row and in addition in Column R have an additional conditional format for the values if they are < or >= 0. Essentially there will be 4 conditions, 1. grey shade and red font 2. grey shade and green font 3. white shade and red font 4. white shade and green font. any suggestions? Use one of your conditions as the default format, then use the others with CF , using the Formula Is option, with the three formulas like =AND(MOD(ROW($Axx),2)=1,$Rxx>=0) =AND(MOD(ROW($Axx),2)=0,$Rxx>=0) =AND(MOD(ROW($Axx),2)=1,$Rxx<0) where xx is the row of the...

Apostrophe vs Text format
Hello- I'm attempting a VLOOKUP. The lookup value is a field that has the little green triangle in the upper left corner of the cell (like when you put an apostrophe before a number) ie 10054 The col_index_nbr in another file is a number 10054 (without the little green triangle). When I attempt a VLOOKUP - it does not work. If I re-type the col_index_nbr so that is begins with an apostrophe, the lookup works. But my file is huge and I can't re-type all of these numbers. If I reformat them to "text", it still does not find a match. Please help. Your key column in th...

Task delegation not working
After reformatting my hard disk and reinstalling Windows, almost everything on my computer works again. The one thing that doesn't is a bizarre change to the way Outlook 2000 handles task delegation. In the past, I could assign a task to a colleague, and it would appear on both my colleague's and my own task lists. When my colleague completed the task, I would get an 'update' message, and the task on my list would be marked as completed. I can still delegate tasks, but I no longer get the automatic updating of my task list when they are complete. On my colleague's compute...

Check if variable is range
This is probably very simple but I just don't see it. How can I see if a (variant) variable is a range or something else (e.g. a string) Sub WhatIsIt() Dim vrString As Variant Dim vrRange1 As Variant Dim vrRange2 As Variant vrString = "This is a string" Set vrRange1 = Range(Cells(1, 1), Cells(1, 2)) 'Note TWO cells included Set vrRange2 = Range(Cells(1, 1), Cells(1, 1)) 'Note ONE cell included 'vrString.copy will not work since vrString is a string 'vrRange1.copy will work since vrRange1 is a range 'vrRange2.copy will work since vr...

2 conditions for condition formatting
dear all, in below table, I need to set the CF in column A when column A and B both are equal to Y. In CF rule, I set below, but A4 doesn't show the highlight color. Please help. ="and($A$1:$A$4=Y,$B$1:$B$4=Y)" colA colB Y N N N N Y Y Y Thanks in advance Pat. Hi Change to =and($A$1:$A$4="Y",$B$1:$B$4="Y") -- Regards Roger Govier "PatLee" <patlee311@gmail.com> wrote in message news:b3861fce-c85b-4d12-8050-81f498778734@n20g2000prh.googlegroups.com... > dear all, > in below table, I n...

condition format for surrounding cells
Need help, I have column A the have 3 conditional format that is color coded depending value, I would like to have columns B, C, D,E (which are text) that could changes to the same color as column A when that changes. If anyone could help that would be greatly appriciated. Hi try something like the following: - select A1:E1 - in the conditional format dialog enter a formula such as =$A1="condition1" -- Regards Frank Kabel Frankfurt, Germany "little rusty with excel" <little rusty with excel@discussions.microsoft.com> schrieb im Newsbeitrag news:E9563E6B-7BCF-4B2...

Check Processing Question
Our checkwriter has asked the following questions: 1). Can you void a check after it has been posted? If so, how? 2). What is the bext way to pay a range of invoices for a single vendor with a discount? The problems we have encountered are as follows: a). When you select a range of invoices for a single vendor the program calculates the discount based on the vendor terms. But if there are one or more invoices selected in the range that we do not wish to pay, unchecking them does not recalculate the discount. Is there a way to force a recalculation of this discount? Is there...

vs 2010 Premium
Hi all, Our original system is developed using ".Net Framework, version=v2.0" and I used vs 2005 Team Suite as development tool. About one month ago, one of our developers upgraded the development tool to vs 2010. But the project in the system is still targeting ".Net Framework, version=v2.0". So I installed vs 2010 premium on my computer. However, when I opened one solution file, it pops up a "Project Target Framework not installed" windows. The message states that "The web project XXXX is targeting ".netFramework, Version =v2.0", ...

Delegations?
Hi all, at work I am trying to set up a delegation. I am the boss and going on holiday....I need my delegate (another member of my team) to be able to access my email. I have set him up as a delegate with the correct permissions BUT, is there any way he can gain access to my outlook inbox automatically without having to do the FILE >> OPEN >> etc thing? TIA, PE1 The mailbox owner (you) needs to grant Reviewer permission to the root of the mailbox, as well as appropriate permission on the folder. The user who needs access then goes into Tools | E-mail Accounts or Tools | Servic...

Too much access using Delegates.
Scenerio: Windows 2000 Server, Exchange 2000, Outlook 2000 & XP mail clients. 10 Users, all are in the Domain Users Group, Each User's MailBox Permissions is set to Defualt - None. Without even adding anyone to the Delegates Tab List, users are able to add additional mail boxes, and view the complete Mailbox tree of the added user. We are looking to implement Delegates, but I haven't been able to limit what users view additional mail boxes. Thanks, Tim Sounds like someone mucked with the original/default Exchange permissions. This doesn't happen by default. See the...

Delegate permissions lost after migration
G'day Group, Currently we have a exchange 5.5 and 2003 server running. We've migrated a small pilot group but i've noticed the following: When the users were migrated I cannot seem to set the Delegate permissions. From Outlook 2003>Tools>Options>Select Delegates. I add the proper user, add views and click apply>OK. Go back to double check the permissions and the delegate I've just added is gone. For some reason it is not retaining the settings. Not too sure what else to look into. Anyhelp would be appreciated. ...

Mail Delegates
I have imported address books for our salespeople and want my department to be able to send out "blast" emails on their behalf. All of the permissions seem to be set just fine, BUT... when I send out the email merge, the sender shows as me not the salesperson that I've chosen. I know I can go into options and select the "reply to" email address, I've also choses options, "From" and put in the salesperson's email address. What am I doing wrong?? Thanks. Dana ...

Pivot charts in 2007 vs 200x
Hello to all, In older versions of Excel, you always had the page list in a pivot chart. Where have they gone to in Excel 2007. If they are no more available directly in the chart, is there a way to get around this anoyance? Thanks for your answers. Stephane "Steve" Halle Hi, This has been replace by the PivotChart Filter Pane which you can expose by selecting the pivot chart and choosing PivotChart Tools, Analyze, PivotChart Filter. -- If this helps, please click the Yes button. Cheers, Shane Devenshire "billardquebec@gmail.com" wrote: > Hello to all, &g...

Displaying values vs formulas
I'm having another brain-dead moment and I hope someone can resuscitate! I'm putting formulas in various cells on a worksheet and some of them are displaying the results and some are just showing in the cell as the formula. How can I get them all to display results. I swear that all the cells are formatted the same but the displays are different. What am I doing wrong? Thanks for any help. Gary Vocks The cells displaying the formula itself and not the results are probably formatted as Text. A quick way to find out if this is so, is to select a cell that displays the formula, the...

OEM vs. fresh install on new Dell server?
Hello! In the old days of Server 2003 or SBS 2003 I always formatted a Dell server and did a fresh installation in order to avoid potential problems such as those that arose with Server 2003 Dell installations and service pack (I forgot...maybe SP1?) on a domain controller. Under certain conditions, they would BSOD on reboot after the SP was installed. Plus, they end up with some really weird user names, remnants of their imaged(?) installations. Anyway, the question is, with Server 2008 R2 on a new Dell server, would it be better to do a fresh installation? I have not instal...

Delegation
If accidently deleted an user's account with mailbox. After re-create the user account, how to recover the user mailbox? Em Yeu wrote: > If accidently deleted an user's account with mailbox. > After re-create the user account, how to recover the user mailbox? Answered your other post. -- Henrik Walther Exchange MVP Exchange-faq.dk MSExchange.org ...

Distribution groups vs. Security Groups
I'm running Exchange 2003. Having a weird ongoing problem. Sometimes my distribution groups change magically to security groups! Someone said you can't use distribution groups to set permissions on calendars (and that doing so will change it from dist to sec)...but when you go to share out your calendar the only groups that show up are distribution groups. This is somehow related to another problem with people sharing out their calendars, sometimes the permissions disappear and people lose access. Help??!!! -- TIA! -- TIA! Ki We had an issue where distribution groups used ...

delegates
i have a user who tries isremoving a delegate from their list but when she comes out and goes back into the list the delegate reappears! any ideas anyone? ...

Pasting conditional cell formatting onto other cells
Suppose you have a matrix of cells, say in C11:D12 for simplicity, upon which you have imposed a conditional formatting scheme, so that, for example, cell C11 is shaded yellow and D12 is shaded cyan. Also suppose that the matrix in C11:D12 was derived from a matrix in A1:B2. Is there a simple way to impose the shading in the C11:D12 matrix onto the matrix in A1:B2, even though the conditional formatting imposed on C11:D12 is not applicable to A1:B2? Example: Here is C11:D12: 0.76 0.98 0.99 0.22 We impose on this matrix the conditional formatting scheme that all values between 0.50 an...

Delegation
I am delegated to have all permission to access my boss email. I have some doubts: a) When i reply mails on my boss behalf , in the "To:" field it shows my name as the sender. Can it be done such tat it shows my boss name? b) After reply or send mail on my boss behalf, all sent mails go to my "Sent Items". Can it be configure that it goes to my boss sent items folder? 1) The Exchange administrator would need to grant you Send As permission on the boss' account. 2) See http://support.microsoft.com/default.aspx?scid=kb;en-us;317865&Product=ol2002 for available s...

COM specs for VS 6
About three years ago i've downloaded a complete specifications of VS6 COM interface from somewhere. IIRC that were 200+ pages or so. That was in the other company. And now I need it back but can't find it anymore. If someone could tell where to find, you'd make me really happy. TIA, Hans -- The one who doesn't know the answer is wiser than the one who knows the wrong answer. ...

Condition Format #1
I have enclosed a chart with this explanation below. I am needing automate this chart according to the following rules. See chart also, if necessary. Thank you. First Whenever, a 3 digit numeric combination is entered into B, C and D cells and if each of the 3 digits are different (ie.3,7,2), then find the 3 cells on the same row between O and BG that have the corresponding boxed the 2 digit pairs. (O=01, P=02, Q=03, R=04, S=05, T=06, U=07, V=08, W=09, X=12, Y=13, Z=14, AA=15, AB=16, AC=17, AD=18, AE=19, AF=23, AG=24, AH=25, AI=26, AJ=27, AK=28, AL=29, AM=34, AN=35, AO=36, AP=37, AQ=38, AR=39...

Check Printingon Blank Check Stock
Newby question: Can GP print on blank check stock using an out-of-the-box installation or do you need an additional module/add-on to print checks onto blank check stock. We have GP version 8 installed with Service Pack 3 and we are using SQL Server 2000. Thanks, Nawaz Great Plains won't properly print the MICR numbers at the bottom of the check that indicate the routing and account information. You will have to use an ISV product such as Mekorma MICR. See: http://www.mekorma.com/ There are other products as well. "Nawaz" wrote: > Newby question: Can GP print on bl...