"is" vs. "as"

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bobby C. Jones

    "is" vs. "as"

    Is there an advantage to either of these methods, or is it simply a matter
    of style? I used to use the "as" method, but later gave it up for the "is"
    method as the intent of the code seems a little clearer to me. I now have
    some projects coming up where the baseTypeCollect ion will contain 5k to 10k
    objects that will have to be searched for various sub types of which I only
    expect to find ~50 to ~100 matches. Thanks!

    foreach (baseType in baseTypeCollect ion)
    {
    if (baseType is desiredSubType)
    {
    typeFound = (desiredSubType ) baseType;
    //do my thing with typeFound
    }
    }


    foreach (baseType in baseTypeCollect ion)
    {
    typeFound = baseType as desiredSubType;
    if (typeFound != null)
    {
    //do my thing with typeFound
    }
    }

    --
    Bobby C. Jones



  • news.microsoft.com

    #2
    Re: "is&quo t; vs. "as&quo t;

    Well the first one is more natural to read.


    "Bobby C. Jones" <bobbyj (at) acadx (dot) com> wrote in message
    news:#gqxrT8nDH A.2808@TK2MSFTN GP10.phx.gbl...[color=blue]
    > Is there an advantage to either of these methods, or is it simply a matter
    > of style? I used to use the "as" method, but later gave it up for the[/color]
    "is"[color=blue]
    > method as the intent of the code seems a little clearer to me. I now have
    > some projects coming up where the baseTypeCollect ion will contain 5k to[/color]
    10k[color=blue]
    > objects that will have to be searched for various sub types of which I[/color]
    only[color=blue]
    > expect to find ~50 to ~100 matches. Thanks!
    >
    > foreach (baseType in baseTypeCollect ion)
    > {
    > if (baseType is desiredSubType)
    > {
    > typeFound = (desiredSubType ) baseType;
    > //do my thing with typeFound
    > }
    > }
    >
    >
    > foreach (baseType in baseTypeCollect ion)
    > {
    > typeFound = baseType as desiredSubType;
    > if (typeFound != null)
    > {
    > //do my thing with typeFound
    > }
    > }
    >
    > --
    > Bobby C. Jones
    > www.AcadX.com
    >
    >[/color]


    Comment

    • Daniel Pratt

      #3
      Re: &quot;is&quo t; vs. &quot;as&quo t;

      Hi Bobby,

      "Bobby C. Jones" <bobbyj (at) acadx (dot) com> wrote in message
      news:%23gqxrT8n DHA.2808@TK2MSF TNGP10.phx.gbl. ..[color=blue]
      > Is there an advantage to either of these methods, or is it simply a matter
      > of style? I used to use the "as" method, but later gave it up for the[/color]
      "is"[color=blue]
      > method as the intent of the code seems a little clearer to me. I now have
      > some projects coming up where the baseTypeCollect ion will contain 5k to[/color]
      10k[color=blue]
      > objects that will have to be searched for various sub types of which I[/color]
      only[color=blue]
      > expect to find ~50 to ~100 matches. Thanks!
      >
      > foreach (baseType in baseTypeCollect ion)
      > {
      > if (baseType is desiredSubType)
      > {
      > typeFound = (desiredSubType ) baseType;
      > //do my thing with typeFound
      > }
      > }
      >
      >
      > foreach (baseType in baseTypeCollect ion)
      > {
      > typeFound = baseType as desiredSubType;
      > if (typeFound != null)
      > {
      > //do my thing with typeFound
      > }
      > }[/color]

      Using "as" is more performat than using "is" because there is only one
      cast instead of two. In most scenarios I would say the difference is
      negligable, but given your scenario, you may just notice a difference.

      Regards,
      Dan


      Comment

      • Nicholas Paldino [.NET/C# MVP]

        #4
        Re: &quot;is&quo t; vs. &quot;as&quo t;

        Bobby,

        In a previous post, Greg Ewing found that when doing comparisons with
        is, it is about 10X faster then checking using "as" or doing an equality
        operation with GetType/typeof.

        However, for what you are doing, I think that you can go one step
        further. I think that what you should do is in your collection, have a
        hashtable. This hashtable should be keyed on the type of the items that are
        kept in the collection. The values in the hashtable are collections of the
        items of that type.

        So, when you add an element, you would check the type. Then look in the
        hashtable against that type. Get the collection of items of that type, and
        add a reference to the new value in your collection there. Also, make sure
        to do the same when deleting.

        Then, when you want to query for the elements that are of a particular
        type, you don't have to enumerate through such a large number of items.
        Granted, the insert and deletes are going to be a little slower, but
        overall, if you do this kind of select often, it should increase the overall
        efficiency of the class.

        Hope this helps.


        --
        - Nicholas Paldino [.NET/C# MVP]
        - mvp@spam.guard. caspershouse.co m

        "Bobby C. Jones" <bobbyj (at) acadx (dot) com> wrote in message
        news:%23gqxrT8n DHA.2808@TK2MSF TNGP10.phx.gbl. ..[color=blue]
        > Is there an advantage to either of these methods, or is it simply a matter
        > of style? I used to use the "as" method, but later gave it up for the[/color]
        "is"[color=blue]
        > method as the intent of the code seems a little clearer to me. I now have
        > some projects coming up where the baseTypeCollect ion will contain 5k to[/color]
        10k[color=blue]
        > objects that will have to be searched for various sub types of which I[/color]
        only[color=blue]
        > expect to find ~50 to ~100 matches. Thanks!
        >
        > foreach (baseType in baseTypeCollect ion)
        > {
        > if (baseType is desiredSubType)
        > {
        > typeFound = (desiredSubType ) baseType;
        > //do my thing with typeFound
        > }
        > }
        >
        >
        > foreach (baseType in baseTypeCollect ion)
        > {
        > typeFound = baseType as desiredSubType;
        > if (typeFound != null)
        > {
        > //do my thing with typeFound
        > }
        > }
        >
        > --
        > Bobby C. Jones
        > www.AcadX.com
        >
        >[/color]


        Comment

        • Bobby C. Jones

          #5
          Re: &quot;is&quo t; vs. &quot;as&quo t;

          Thanks Nicholas and everyone! This is some great info to know.

          The collection is actually one that I am receiving from a COM server, not
          one that I'm creating myself. I had actually considered something like what
          you are suggesting here Nicholas as the COM server does provide event
          notification when objects are added and removed. But I wanted to wait and
          see if iterating the entire collection will become a bottleneck or not
          before adding the code to optimize the searches. This could be feasible and
          not to damaging to my app's memory footprint because I won't need to search
          for all of the subtypes, only a handful. I could just cache those types, or
          even dynamically cache them as needed...Hmm... thanks for helping to get the
          brain juices flowing!
          --
          Bobby C. Jones



          Comment

          • news.microsoft.com

            #6
            Re: &quot;is&quo t; vs. &quot;as&quo t;

            You cant have duplicates in a Hashtable so how do you propose keying on
            Type? Only one type alowed at any one time?


            "Bobby C. Jones" <bobbyj (at) acadx (dot) com> wrote in message
            news:#Aa0qz8nDH A.2652@TK2MSFTN GP09.phx.gbl...[color=blue]
            > Thanks Nicholas and everyone! This is some great info to know.
            >
            > The collection is actually one that I am receiving from a COM server, not
            > one that I'm creating myself. I had actually considered something like[/color]
            what[color=blue]
            > you are suggesting here Nicholas as the COM server does provide event
            > notification when objects are added and removed. But I wanted to wait and
            > see if iterating the entire collection will become a bottleneck or not
            > before adding the code to optimize the searches. This could be feasible[/color]
            and[color=blue]
            > not to damaging to my app's memory footprint because I won't need to[/color]
            search[color=blue]
            > for all of the subtypes, only a handful. I could just cache those types,[/color]
            or[color=blue]
            > even dynamically cache them as needed...Hmm... thanks for helping to get[/color]
            the[color=blue]
            > brain juices flowing!
            > --
            > Bobby C. Jones
            > www.AcadX.com
            >
            >[/color]


            Comment

            • Jon Skeet [C# MVP]

              #7
              Re: &quot;is&quo t; vs. &quot;as&quo t;

              Nicholas Paldino [.NET/C# MVP] <mvp@spam.guard .caspershouse.c om> wrote:[color=blue]
              > In a previous post, Greg Ewing found that when doing comparisons with
              > is, it is about 10X faster then checking using "as" or doing an equality
              > operation with GetType/typeof.[/color]

              No - he found it was ten times faster than doing an equality check with
              GetType/typeof. as/is were roughly the same speed, I believe - that
              would certainly make sense, although if you then need to cast, "as"
              should be faster.

              --
              Jon Skeet - <skeet@pobox.co m>
              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

              If replying to the group, please do not mail me too

              Comment

              • Nicholas Paldino [.NET/C# MVP]

                #8
                Re: &quot;is&quo t; vs. &quot;as&quo t;

                The original poster (OP) indicated that the collection was storing
                references of a base type. He is searching for the derived types in the
                collection. The hashtable is going to be keyed on the type of the value
                that is stored in the collection (GetType returns the type of the instance,
                not the type of the reference).

                The hashtable would store another collection, which has the references
                to the values that are in the main collection, and provides an easy way to
                look them up based on the type.


                --
                - Nicholas Paldino [.NET/C# MVP]
                - mvp@spam.guard. caspershouse.co m

                "news.microsoft .com" <discussion@dis cussion.microso ft.com> wrote in message
                news:uACZN28nDH A.2964@tk2msftn gp13.phx.gbl...[color=blue]
                > You cant have duplicates in a Hashtable so how do you propose keying on
                > Type? Only one type alowed at any one time?
                >
                >
                > "Bobby C. Jones" <bobbyj (at) acadx (dot) com> wrote in message
                > news:#Aa0qz8nDH A.2652@TK2MSFTN GP09.phx.gbl...[color=green]
                > > Thanks Nicholas and everyone! This is some great info to know.
                > >
                > > The collection is actually one that I am receiving from a COM server,[/color][/color]
                not[color=blue][color=green]
                > > one that I'm creating myself. I had actually considered something like[/color]
                > what[color=green]
                > > you are suggesting here Nicholas as the COM server does provide event
                > > notification when objects are added and removed. But I wanted to wait[/color][/color]
                and[color=blue][color=green]
                > > see if iterating the entire collection will become a bottleneck or not
                > > before adding the code to optimize the searches. This could be feasible[/color]
                > and[color=green]
                > > not to damaging to my app's memory footprint because I won't need to[/color]
                > search[color=green]
                > > for all of the subtypes, only a handful. I could just cache those[/color][/color]
                types,[color=blue]
                > or[color=green]
                > > even dynamically cache them as needed...Hmm... thanks for helping to get[/color]
                > the[color=green]
                > > brain juices flowing!
                > > --
                > > Bobby C. Jones
                > > www.AcadX.com
                > >
                > >[/color]
                >
                >[/color]


                Comment

                • Nicholas Paldino [.NET/C# MVP]

                  #9
                  Re: &quot;is&quo t; vs. &quot;as&quo t;

                  Jon,

                  Nope, these are the numbers that he posted:

                  Using the is operator took 00:00:00.000024 0
                  Using GetType() took 00:00:00.000236 3
                  Using the as operator took 00:00:00.000239 4

                  The as operator was the slowest of them all.

                  --
                  - Nicholas Paldino [.NET/C# MVP]
                  - mvp@spam.guard. caspershouse.co m

                  "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                  news:MPG.1a0ca1 c9bc29a9289899c e@msnews.micros oft.com...[color=blue]
                  > Nicholas Paldino [.NET/C# MVP] <mvp@spam.guard .caspershouse.c om> wrote:[color=green]
                  > > In a previous post, Greg Ewing found that when doing comparisons[/color][/color]
                  with[color=blue][color=green]
                  > > is, it is about 10X faster then checking using "as" or doing an equality
                  > > operation with GetType/typeof.[/color]
                  >
                  > No - he found it was ten times faster than doing an equality check with
                  > GetType/typeof. as/is were roughly the same speed, I believe - that
                  > would certainly make sense, although if you then need to cast, "as"
                  > should be faster.
                  >
                  > --
                  > Jon Skeet - <skeet@pobox.co m>
                  > http://www.pobox.com/~skeet
                  > If replying to the group, please do not mail me too[/color]


                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    Re: &quot;is&quo t; vs. &quot;as&quo t;

                    Nicholas Paldino [.NET/C# MVP] <mvp@spam.guard .caspershouse.c om> wrote:[color=blue]
                    > Nope, these are the numbers that he posted:
                    >
                    > Using the is operator took 00:00:00.000024 0
                    > Using GetType() took 00:00:00.000236 3
                    > Using the as operator took 00:00:00.000239 4
                    >
                    > The as operator was the slowest of them all.[/color]

                    Oops. In that case, I'm afraid I question the testing methodology *or*
                    Whidbey has *completely* different behaviour to v1.1, which it may do
                    for the beta, of course.

                    (Note that the code originally posted didn't even test it 1000 times,
                    so I'm assuming that wasn't the code that was actually run.)

                    Here's code that can run under .NET 1.1, and then the results:

                    using System;
                    using System.Web;
                    using System.Web.UI;
                    using System.Web.UI.W ebControls;

                    class Stopwatch
                    {
                    DateTime start;
                    DateTime stop;

                    internal TimeSpan Elapsed
                    {
                    get
                    {
                    return stop-start;
                    }
                    }

                    internal void Start()
                    {
                    start = DateTime.Now;
                    }

                    internal void Stop()
                    {
                    stop = DateTime.Now;
                    }
                    }

                    class Class1
                    {

                    const int Iterations = 100000000;

                    static void Main(string[] args)
                    {
                    Control ctl = new DropDownList();
                    Stopwatch sw = new Stopwatch();
                    int j = 0;
                    sw.Start();
                    for (int i = 0; i < Iterations; i++)
                    {
                    if (ctl is System.Web.UI.W ebControls.Drop DownList)
                    {
                    j++;
                    //Console.WriteLi ne("ctl is a DropDownList");
                    }
                    else
                    {
                    j++;
                    //Console.WriteLi ne("ctl is NOT a DropDownList");
                    }
                    }
                    sw.Stop();
                    Console.WriteLi ne("Using the is operator took " + sw.Elapsed);

                    sw.Start();
                    for (int i = 0; i < Iterations; i++)
                    {
                    if (ctl.GetType() == typeof
                    System.Web.UI.W ebControls.Drop DownList))
                    {
                    j++;
                    //Console.WriteLi ne("ctl is a DropDownList");
                    }
                    else
                    {
                    j++;
                    //Console.WriteLi ne("ctl is NOT a DropDownList");
                    }
                    }

                    sw.Stop();
                    Console.WriteLi ne("Using GetType() took " + sw.Elapsed);

                    sw.Start();
                    for (int i=0; i < Iterations; i++)
                    {
                    if ((ctl as System.Web.UI.W ebControls.Drop DownList)
                    != null)
                    {
                    j++;
                    //Console.WriteLi ne("ctl is a DropDownList");
                    }
                    else
                    {
                    j++;
                    //Console.WriteLi ne("ctl is NOT a DropDownList");
                    }
                    }
                    sw.Stop();
                    Console.WriteLi ne("Using the as operator took " + sw.Elapsed);
                    Console.Read();
                    }
                    }

                    My results:
                    Using the is operator took 00:00:00.703125 0
                    Using GetType() took 00:00:04.953125 0
                    Using the as operator took 00:00:00.500000 0

                    Looking at the IL for the as/is cases, they look identical to me (I
                    suspect the variance in time shown above is due to JITting through the
                    as case, but I haven't investigated further). As I understand it,

                    if (x is Y)

                    is always transformed into exactly the same code as

                    if ((x as Y) != null)


                    When you then cast, it's cheaper to just use "as" a single time, as
                    that only requires the check to be performed once.

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                    If replying to the group, please do not mail me too

                    Comment

                    • Pieter Philippaerts

                      #11
                      Re: &quot;is&quo t; vs. &quot;as&quo t;

                      "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message[color=blue]
                      > Looking at the IL for the as/is cases, they look identical to me (I
                      > suspect the variance in time shown above is due to JITting through the
                      > as case, but I haven't investigated further). As I understand it,[/color]

                      I also get similar performance for 'as' and 'is' on framework 1.0.
                      [color=blue]
                      > if (x is Y)
                      > is always transformed into exactly the same code as
                      > if ((x as Y) != null)[/color]

                      On the contrary, if you look at the IL you see that 'as' is converted to an
                      'is'. This makes sense because 'as' cannot be used for value types, while
                      'is' can.

                      Regards,
                      Pieter Philippaerts
                      Managed SSL/TLS: http://www.mentalis.org/go.php?sl


                      Comment

                      • news.microsoft.com

                        #12
                        Re: &quot;is&quo t; vs. &quot;as&quo t;

                        Dont use DateTime

                        Wrap QueryPerformanc eCounter and QueryPerformanc eFrequency native API



                        "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                        news:MPG.1a0ca9 c3ce5791fb9899d 1@msnews.micros oft.com...[color=blue]
                        > Nicholas Paldino [.NET/C# MVP] <mvp@spam.guard .caspershouse.c om> wrote:[color=green]
                        > > Nope, these are the numbers that he posted:
                        > >
                        > > Using the is operator took 00:00:00.000024 0
                        > > Using GetType() took 00:00:00.000236 3
                        > > Using the as operator took 00:00:00.000239 4
                        > >
                        > > The as operator was the slowest of them all.[/color]
                        >
                        > Oops. In that case, I'm afraid I question the testing methodology *or*
                        > Whidbey has *completely* different behaviour to v1.1, which it may do
                        > for the beta, of course.
                        >
                        > (Note that the code originally posted didn't even test it 1000 times,
                        > so I'm assuming that wasn't the code that was actually run.)
                        >
                        > Here's code that can run under .NET 1.1, and then the results:
                        >
                        > using System;
                        > using System.Web;
                        > using System.Web.UI;
                        > using System.Web.UI.W ebControls;
                        >
                        > class Stopwatch
                        > {
                        > DateTime start;
                        > DateTime stop;
                        >
                        > internal TimeSpan Elapsed
                        > {
                        > get
                        > {
                        > return stop-start;
                        > }
                        > }
                        >
                        > internal void Start()
                        > {
                        > start = DateTime.Now;
                        > }
                        >
                        > internal void Stop()
                        > {
                        > stop = DateTime.Now;
                        > }
                        > }
                        >
                        > class Class1
                        > {
                        >
                        > const int Iterations = 100000000;
                        >
                        > static void Main(string[] args)
                        > {
                        > Control ctl = new DropDownList();
                        > Stopwatch sw = new Stopwatch();
                        > int j = 0;
                        > sw.Start();
                        > for (int i = 0; i < Iterations; i++)
                        > {
                        > if (ctl is System.Web.UI.W ebControls.Drop DownList)
                        > {
                        > j++;
                        > //Console.WriteLi ne("ctl is a DropDownList");
                        > }
                        > else
                        > {
                        > j++;
                        > //Console.WriteLi ne("ctl is NOT a DropDownList");
                        > }
                        > }
                        > sw.Stop();
                        > Console.WriteLi ne("Using the is operator took " + sw.Elapsed);
                        >
                        > sw.Start();
                        > for (int i = 0; i < Iterations; i++)
                        > {
                        > if (ctl.GetType() == typeof
                        > System.Web.UI.W ebControls.Drop DownList))
                        > {
                        > j++;
                        > //Console.WriteLi ne("ctl is a DropDownList");
                        > }
                        > else
                        > {
                        > j++;
                        > //Console.WriteLi ne("ctl is NOT a DropDownList");
                        > }
                        > }
                        >
                        > sw.Stop();
                        > Console.WriteLi ne("Using GetType() took " + sw.Elapsed);
                        >
                        > sw.Start();
                        > for (int i=0; i < Iterations; i++)
                        > {
                        > if ((ctl as System.Web.UI.W ebControls.Drop DownList)
                        > != null)
                        > {
                        > j++;
                        > //Console.WriteLi ne("ctl is a DropDownList");
                        > }
                        > else
                        > {
                        > j++;
                        > //Console.WriteLi ne("ctl is NOT a DropDownList");
                        > }
                        > }
                        > sw.Stop();
                        > Console.WriteLi ne("Using the as operator took " + sw.Elapsed);
                        > Console.Read();
                        > }
                        > }
                        >
                        > My results:
                        > Using the is operator took 00:00:00.703125 0
                        > Using GetType() took 00:00:04.953125 0
                        > Using the as operator took 00:00:00.500000 0
                        >
                        > Looking at the IL for the as/is cases, they look identical to me (I
                        > suspect the variance in time shown above is due to JITting through the
                        > as case, but I haven't investigated further). As I understand it,
                        >
                        > if (x is Y)
                        >
                        > is always transformed into exactly the same code as
                        >
                        > if ((x as Y) != null)
                        >
                        >
                        > When you then cast, it's cheaper to just use "as" a single time, as
                        > that only requires the check to be performed once.
                        >
                        > --
                        > Jon Skeet - <skeet@pobox.co m>
                        > http://www.pobox.com/~skeet
                        > If replying to the group, please do not mail me too[/color]


                        Comment

                        • Pieter Philippaerts

                          #13
                          Re: &quot;is&quo t; vs. &quot;as&quo t;

                          "news.microsoft .com" <discussion@dis cussion.microso ft.com> wrote[color=blue]
                          > Dont use DateTime[/color]

                          If you're using enough iterations, DateTime is fine. On my computer the
                          different loops take between 1.3s and 11s. If you know that DateTime has a
                          resolution of around 10ms, I'm sure that you'll agree it's good enough.

                          Regards,
                          Pieter Philippaerts
                          Managed SSL/TLS: http://www.mentalis.org/go.php?sl


                          Comment

                          • Willy Denoyette [MVP]

                            #14
                            Re: &quot;is&quo t; vs. &quot;as&quo t;

                            Jon,

                            FYI these are the whidbey results on a 1Ghz PIII

                            Using the is operator took 00:00:01.131593 3
                            Using GetType() took 00:00:02.663750 6
                            Using the as operator took 00:00:01.021438 2

                            Good to see GetType got a los faster (as a lot of others :-))
                            Willy.

                            "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message news:MPG.1a0ca9 c3ce5791fb9899d 1@msnews.micros oft.com...[color=blue]
                            > Nicholas Paldino [.NET/C# MVP] <mvp@spam.guard .caspershouse.c om> wrote:[color=green]
                            > > Nope, these are the numbers that he posted:
                            > >
                            > > Using the is operator took 00:00:00.000024 0
                            > > Using GetType() took 00:00:00.000236 3
                            > > Using the as operator took 00:00:00.000239 4
                            > >
                            > > The as operator was the slowest of them all.[/color]
                            >
                            > Oops. In that case, I'm afraid I question the testing methodology *or*
                            > Whidbey has *completely* different behaviour to v1.1, which it may do
                            > for the beta, of course.
                            >
                            > (Note that the code originally posted didn't even test it 1000 times,
                            > so I'm assuming that wasn't the code that was actually run.)
                            >
                            > Here's code that can run under .NET 1.1, and then the results:
                            >
                            > using System;
                            > using System.Web;
                            > using System.Web.UI;
                            > using System.Web.UI.W ebControls;
                            >
                            > class Stopwatch
                            > {
                            > DateTime start;
                            > DateTime stop;
                            >
                            > internal TimeSpan Elapsed
                            > {
                            > get
                            > {
                            > return stop-start;
                            > }
                            > }
                            >
                            > internal void Start()
                            > {
                            > start = DateTime.Now;
                            > }
                            >
                            > internal void Stop()
                            > {
                            > stop = DateTime.Now;
                            > }
                            > }
                            >
                            > class Class1
                            > {
                            >
                            > const int Iterations = 100000000;
                            >
                            > static void Main(string[] args)
                            > {
                            > Control ctl = new DropDownList();
                            > Stopwatch sw = new Stopwatch();
                            > int j = 0;
                            > sw.Start();
                            > for (int i = 0; i < Iterations; i++)
                            > {
                            > if (ctl is System.Web.UI.W ebControls.Drop DownList)
                            > {
                            > j++;
                            > //Console.WriteLi ne("ctl is a DropDownList");
                            > }
                            > else
                            > {
                            > j++;
                            > //Console.WriteLi ne("ctl is NOT a DropDownList");
                            > }
                            > }
                            > sw.Stop();
                            > Console.WriteLi ne("Using the is operator took " + sw.Elapsed);
                            >
                            > sw.Start();
                            > for (int i = 0; i < Iterations; i++)
                            > {
                            > if (ctl.GetType() == typeof
                            > System.Web.UI.W ebControls.Drop DownList))
                            > {
                            > j++;
                            > //Console.WriteLi ne("ctl is a DropDownList");
                            > }
                            > else
                            > {
                            > j++;
                            > //Console.WriteLi ne("ctl is NOT a DropDownList");
                            > }
                            > }
                            >
                            > sw.Stop();
                            > Console.WriteLi ne("Using GetType() took " + sw.Elapsed);
                            >
                            > sw.Start();
                            > for (int i=0; i < Iterations; i++)
                            > {
                            > if ((ctl as System.Web.UI.W ebControls.Drop DownList)
                            > != null)
                            > {
                            > j++;
                            > //Console.WriteLi ne("ctl is a DropDownList");
                            > }
                            > else
                            > {
                            > j++;
                            > //Console.WriteLi ne("ctl is NOT a DropDownList");
                            > }
                            > }
                            > sw.Stop();
                            > Console.WriteLi ne("Using the as operator took " + sw.Elapsed);
                            > Console.Read();
                            > }
                            > }
                            >
                            > My results:
                            > Using the is operator took 00:00:00.703125 0
                            > Using GetType() took 00:00:04.953125 0
                            > Using the as operator took 00:00:00.500000 0
                            >
                            > Looking at the IL for the as/is cases, they look identical to me (I
                            > suspect the variance in time shown above is due to JITting through the
                            > as case, but I haven't investigated further). As I understand it,
                            >
                            > if (x is Y)
                            >
                            > is always transformed into exactly the same code as
                            >
                            > if ((x as Y) != null)
                            >
                            >
                            > When you then cast, it's cheaper to just use "as" a single time, as
                            > that only requires the check to be performed once.
                            >
                            > --
                            > Jon Skeet - <skeet@pobox.co m>
                            > http://www.pobox.com/~skeet
                            > If replying to the group, please do not mail me too[/color]


                            Comment

                            • Alvin Bruney

                              #15
                              Re: &quot;is&quo t; vs. &quot;as&quo t;

                              > In a previous post, Greg Ewing found that when doing comparisons with[color=blue]
                              > is, it is about 10X faster then checking using "as" or doing an equality
                              > operation with GetType/typeof.[/color]

                              That doesn't seem to be correct???

                              --


                              -----------
                              Got TidBits?
                              Get it here: www.networkip.net/tidbits
                              "Nicholas Paldino [.NET/C# MVP]" <mvp@spam.guard .caspershouse.c om> wrote in
                              message news:e#kTxg8nDH A.2528@TK2MSFTN GP12.phx.gbl...[color=blue]
                              > Bobby,
                              >
                              > In a previous post, Greg Ewing found that when doing comparisons with
                              > is, it is about 10X faster then checking using "as" or doing an equality
                              > operation with GetType/typeof.
                              >
                              > However, for what you are doing, I think that you can go one step
                              > further. I think that what you should do is in your collection, have a
                              > hashtable. This hashtable should be keyed on the type of the items that[/color]
                              are[color=blue]
                              > kept in the collection. The values in the hashtable are collections of[/color]
                              the[color=blue]
                              > items of that type.
                              >
                              > So, when you add an element, you would check the type. Then look in[/color]
                              the[color=blue]
                              > hashtable against that type. Get the collection of items of that type,[/color]
                              and[color=blue]
                              > add a reference to the new value in your collection there. Also, make[/color]
                              sure[color=blue]
                              > to do the same when deleting.
                              >
                              > Then, when you want to query for the elements that are of a particular
                              > type, you don't have to enumerate through such a large number of items.
                              > Granted, the insert and deletes are going to be a little slower, but
                              > overall, if you do this kind of select often, it should increase the[/color]
                              overall[color=blue]
                              > efficiency of the class.
                              >
                              > Hope this helps.
                              >
                              >
                              > --
                              > - Nicholas Paldino [.NET/C# MVP]
                              > - mvp@spam.guard. caspershouse.co m
                              >
                              > "Bobby C. Jones" <bobbyj (at) acadx (dot) com> wrote in message
                              > news:%23gqxrT8n DHA.2808@TK2MSF TNGP10.phx.gbl. ..[color=green]
                              > > Is there an advantage to either of these methods, or is it simply a[/color][/color]
                              matter[color=blue][color=green]
                              > > of style? I used to use the "as" method, but later gave it up for the[/color]
                              > "is"[color=green]
                              > > method as the intent of the code seems a little clearer to me. I now[/color][/color]
                              have[color=blue][color=green]
                              > > some projects coming up where the baseTypeCollect ion will contain 5k to[/color]
                              > 10k[color=green]
                              > > objects that will have to be searched for various sub types of which I[/color]
                              > only[color=green]
                              > > expect to find ~50 to ~100 matches. Thanks!
                              > >
                              > > foreach (baseType in baseTypeCollect ion)
                              > > {
                              > > if (baseType is desiredSubType)
                              > > {
                              > > typeFound = (desiredSubType ) baseType;
                              > > //do my thing with typeFound
                              > > }
                              > > }
                              > >
                              > >
                              > > foreach (baseType in baseTypeCollect ion)
                              > > {
                              > > typeFound = baseType as desiredSubType;
                              > > if (typeFound != null)
                              > > {
                              > > //do my thing with typeFound
                              > > }
                              > > }
                              > >
                              > > --
                              > > Bobby C. Jones
                              > > www.AcadX.com
                              > >
                              > >[/color]
                              >
                              >[/color]


                              Comment

                              Working...