7 Replies Latest reply on Dec 27, 2006 3:28 PM by Matlus

    Cross-post: Using the "as" operator vs casting

    ntsiii Level 3
      I'm cross posting this because it is technically an Actionscript question, but it has real Flex consequences.

      I've recently been reading the docs regarding data types in AS3 and am still not clear on a few things. If anyone has blogged on this, please point me there.

      One problem is that "casting" syntax is the same as top-level function syntax. Compare String(objString) to XML(event.result). The latter is a top-level function, but the former is a "cast". Or is it?

      An option to the String cast is objString.toString(). What is the difference? I am not so much interested in the underlying details of the language, as in understanding when to use which.

      The same question exists for the top-level function XML(event.result), which can be done with the "as" operator: event.result as XML. When to use which? Are there performance issues? The "as operator" documentation is unsatisfying.

      Any discussion of this will be appreciated.

      Tracy
        • 1. Re: Cross-post: Using the "as" operator vs casting
          buabco Level 1
          Tracy,

          From what I've understand on the documentation the only real TYPE CASTING is by using the "as" operator, when you use the XML(Obj) it's a top level Function.

          The bigger difference I guess it on the return type, by using the "as" operator you never get an error, but you'll get null if the object can't be converted, by using toplevel functions you get an error right away.

          From the performance point of view (I'm guessing here), when you use "as" you are typecasting but when you use a toplevel function you are converting.

          Still would be good if someone from adobe post the performance differences from using one method or another.
          • 2. Re: Cross-post: Using the "as" operator vs casting
            ntsiii Level 3
            Peter Ent said about the same thing you did over on the General Discussion Forum. The main difference is returning an exception vs a null. No indication of the performance issue though.

            If I ever get into a situation where i think the peformance might be a significant factor (or I have some free time!), I'll benchnmark the two options.

            Tracy

            • 3. Re: Cross-post: Using the "as" operator vs casting
              Matlus Level 1
              Tracy,

              When you "cast" you are tell (and not asking) the compiler to cast (or treat/consider) an instance of one class to (be) an instance of another class. This is accomplished at the memory level and tends to be extremely fast in performance.

              The toString() method is actually a "conversion" and not a cast, where each class has it's own implementation of how to "convert" itself to a string representation.

              The "as" operator can be considered a "safe" cast, in that it will first check to see if the object instance can be cast. If it can it will "cast" and if not, it will return a null. So this is a bit slower in terms of performance as compared to a hard cast. But it is safer.

              However, most times, you know that an instance of one class can also be treated as another and so you can cast instead of using the "as" operator.

              You can tell the difference between a cast and a method call when you use the class directly. In your examples(String(objString) & XML(event.result)), both are casts and not top level functions (not sure what top level means :)).

              When to use a cast versus toString()? I started off thinking "simple" but... If you have a few examples of when you'd like to know which to use I'd be happy to answer. In general, you'd use the toString() method if you want to "convert" an instance of a (non String) class to a string. You would/should use a cast if you know the instance is actually a "string" but is say available to you in an instance of Object, like so:
              var o:Object = "22";
              var s:String = String(o);

              I suggest also reading the "Type conversions" section in Live Docs, since Action Script adds a few nuances if it's own.
              • 4. Re: Cross-post: Using the "as" operator vs casting
                buabco Level 1
                Maltus now I'm totally confused.

                The Flex manual in the TOP LEVEL section (Guess TOP LEVEL means that they don't belong to any package) clearly states this functions:

                Function Description
                Array Creates a new array.
                Boolean Converts the expression parameter to a Boolean value and returns the value.
                decodeURI Decodes an encoded URI into a string.
                decodeURIComponent Decodes an encoded URI component into a string.
                encodeURI Encodes a string into a valid URI (Uniform Resource Identifier).
                encodeURIComponent Encodes a string into a valid URI component.
                escape Converts the parameter to a string and encodes it in a URL-encoded format, where most nonalphanumeric characters are replaced with % hexadecimal sequences.
                int Converts a given numeric value to an integer value.
                isFinite Returns true if the value is a finite number, or false if the value is Infinity or -Infinity.
                isNaN Returns true if the value is NaN(not a number).
                isXMLName Determines whether the specified string is a valid name for an XML element or attribute.
                Number Converts a given value to a Number value.
                Object Every value in ActionScript 3.0 is an object, which means that calling Object() on a value returns that value.
                parseFloat Converts a string to a floating-point number.
                parseInt Converts a string to an integer.
                String Returns a string representation of the specified parameter.
                trace Displays expressions, or writes to log files, while debugging.
                uint Converts a given numeric value to an unsigned integer value.
                unescape Evaluates the parameter str as a string, decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters), and returns the string.
                XML Converts an object to an XML object.
                XMLList Converts an object to an XMLList object.

                So how do I do a XML type casting without using the XML function for example? or is it the same?
                • 5. Re: Cross-post: Using the "as" operator vs casting
                  Matlus Level 1
                  Sorry for the confusion :)
                  It seems both String and XML are "top level" functions that return (by conversion and NOT by casting) an instance of a String and XML object respectively.

                  It looks like the ActionScript team decided to have "top level" (or globally accessible) functions as part of the compiler and named them with the names and cases the way they are intentionally, so as to prevent someone for trying to (truly) cast say a String or XML. So when you do cast by using this syntax you only think you're casting, but behind the secenes its actually a conversion.
                  • 6. Re: Cross-post: Using the "as" operator vs casting
                    ntsiii Level 3
                    Yeah, that syntax similarity was a main cause of my own confusion.

                    I may settle on the function/casting option for consistency and readability. If there is a performance difference, it is almost certainly negligible, except in multi-thousand iteration loops, which will be a rare condition anyway.

                    Thanks for all the explanations.

                    Tracy
                    • 7. Re: Cross-post: Using the "as" operator vs casting
                      Matlus Level 1
                      Yes, I agree on the performance point. However, here is another take on things, at least in my mind, when I see code this is what I think.

                      When you use a Cast it kind of tells the person reading the code that, "Yes, I know the instance is of this type X, it just happens to be in a variable of this type Y".

                      When you see a Conversion (as against a cast) you know there is an intent to "convert" type X to type Y. Since you can't always coerce type X to a type Y you *have* to convert.

                      So a Cast or Convert "tells" you something more about:
                      1. The coder's intent
                      2. The coder's understanding (or misunderstanding)
                      3. As code evolves it is possible that when you couldn't cast earlier you can now and vice versa.

                      The rule of thumb I use is: When you can, Cast when you can't, Convert.

                      In all honesty in Flex I'd look at these "top level" functions as "casts" since it looks to me like that's what the AS language designers intended. Sadly, the IDE doesn't have color coding for types so you can't tell by looking code, whether it's a cast or a method call.