Actionscript 3.0 getter setter increment - actionscript-3

private var _variable:int;
public function set variable(val:int):void{
_variable = val;
}
public function get variable():int{
return _variable
}
Now if I have to increment the variable... which one is more optimized way of doing ?
__instance.variable++;
or
__instance.variable = __instance.variable + 1;
The reason for asking this question is, I have read a++ is faster than a = a+1;. Would the same principle apply even when using getters and setters ?

No normally they will be translated the same way because there is no special opcode within the VM to do this operation, the VM will have to do these operations :
read the variable value into a register
increment the register
put back the value
now it's shorter and less error prone to write __instance.variable++ than the second way.
In contrary when you increment a local variable doing var++ it exists a special operation (inclocal or inclocal_i (i stand for integer) ) that will directly increment the value of the register so it can be slightly faster.
Here a list for example of the AVM2 opcode :
http://www.anotherbigidea.com/javaswf/avm2/AVM2Instructions.html

As far as i know there is no gradual difference between these two..
I have read a++ is faster than a = a+1;
Actually this statement of yours is a Paradox.
Because compilers(C compiler in this case) and interprets consider a++ as a=a+1 , so even though you write a++. Its not going to make a huge difference.

Related

A tool to detect unnecessary recursive calls in a program?

A very common beginner mistake when writing recursive functions is to accidentally fire off completely redundant recursive calls from the same function. For example, consider this recursive function that finds the maximum value in a binary tree (not a binary search tree):
int BinaryTreeMax(Tree* root) {
if (root == null) return INT_MIN;
int maxValue = root->value;
if (maxValue < BinaryTreeMax(root->left))
maxValue = BinaryTreeMax(root->left); // (1)
if (maxValue < BinaryTreeMax(root->right))
maxValue = BinaryTreeMax(root->right); // (2)
return maxValue;
}
Notice that this program potentially makes two completely redundant recursive calls to BinaryTreeMax in lines (1) and (2). We could rewrite this code so that there's no need for these extra calls by simply caching the value from before:
int BinaryTreeMax(Tree* root) {
if (root == null) return INT_MIN;
int maxValue = root->value;
int leftValue = BinaryTreeMax(root->left);
int rightValue = BinaryTreeMax(root->right);
if (maxValue < leftValue)
maxValue = leftValue;
if (maxValue < rightValue)
maxValue = rightValue;
return maxValue;
}
Now, we always make exactly two recursive calls.
My question is whether there is a tool that does either a static or dynamic analysis of a program (in whatever language you'd like; I'm not too picky!) that can detect whether a program is making completely unnecessary recursive calls. By "completely unnecessary" I mean that
The recursive call has been made before,
by the same invocation of the recursive function (or one of its descendants), and
the call itself has no observable side-effects.
This is something that can usually be determined by hand, but I think it would be great if there were some tool that could flag things like this automatically as a way of helping students gain feedback about how to avoid making simple but expensive mistakes in their programs that could contribute to huge inefficiencies.
Does anyone know of such a tool?
First, your definition of 'completely unnecessary' is insufficient. It is possible that some code between the two function calls affects the result of the second function call.
Second, this has nothing to do with recursion, the same question can apply to any function call. If it has been called before with the exact same parameters, has no side-effects, and no code between the two calls changed any data the function accesses.
Now, I'm pretty sure a perfect solution is impossible, as it would solve The Halting Problem, but that doesn't mean there isn't a way to detect enough of these cases and optimize away some of them.
Some compilers know how to do that (GCC has a specific flag that warns you when it does so). Here's a 2003 article I found about the issue: http://www.cs.cmu.edu/~jsstylos/15745/final.pdf .
I couldn't find a tool for this, though, but that's probably something Eric Lipert knows, if he happens to bump into your question.
Some compilers (such as GCC) do have ways to mark determinate functions explicitly (to be more precise, __attribute__((const)) (see GCC function attributes) applies some restrictions onto the function body to make its result depend only from its argument and get no depency from shared state of program or other non-deterministic functions). Then they eliminate duplicate calls to costy functions. Some other high-level language implementations (may be Haskell) does this tests automatically.
Really, I don't know tools for such analysis (but if i find it i will be happy). And if there is one that correcly detects unnecessary recursion or, in general way, function evaluation (in language-agnostic environment) it would be a kind of determinacy prover.
BTW, it's not so difficult to write such program when you already have access to semantic tree of the code :)

Where is the return value of a function stored?

I assume this question is language agnostic, and apologies if it's quite rudimentary, but say we have (PHP in this example)
function myFunc() {
return 4;
}
Now when this function is called, usually the result will be used in an expression or be assigned to a variable. But if it's not assigned to a variable, where does the return value "live" when it's been called? Is there an internal structure that keeps it in memory for the purpose of the current statement, and when that statement is executed, it removes it again?
If you just do something like:
var foo = bar();
myFunc();
var wibble = baz();
Then a Number 4 will be created for the return statement, then immediately will be discarded as there aren't any references to it.
(Note: C++ specific) In most cases compiler will user Return Value Optimisation and store value in the variable that gets the result of the function assigned to.
For example:
int myInt = myFunc();
will cause the pointer to myInt varaible to by passed to myFunc on the stack so myFunc will work directly with myInt without creating a new variable.
Otherwise the function returns by placing the return value on the stack.
I think in .NET it's called Name Return Value Optimization.
Other compilers probably have similar features in place.
so say we had a more complex statement like myFunc() + ComplexFunction()
I think this one depends on the compiler and it's register allocation scheme.
The compiler could store the result for myFunc() in a register, then jump to execute ComplexFunction(). On entering ComplexFunction(), the registers would be saved on the stack and the restored when returning.

Variable Declaration Versus Error Checking: Which Comes First?

When writing a function I always have this confusion whether to check for errors first and declare the variables later (or) assign the parameters to local variables and then check for errors. Which of the following way is preferred and why? I usually stick to the first type.
void DoSomething1(Object x, Object y){
// All sort of error checking goes here
if IsError(x) return;
if IsError(y) return;
// Variable declaration
int i,j;
Object z = x;
}
void DoSomething2(Object x, Object y){
// Variable declaration
int i,j;
Object z = x;
// All sort of error checking goes here
if IsError(z) return;
if IsError(y) return;
}
You should follow a proximity rule and declare the variables as late as possible. This localises their creation and use. You should also check parameters for validity at the earliest possible opportunity to minimise the work performed.
Hence I agree that your first one is better but it is subjective. There's possibly arguments for the other approach but I've yet to hear convincing ones, so I consider those two guidelines as best practice.
Since you state "language agnostic" despite the fact your code looks somehow strangely familiar :-), there are almost certainly some languages where you don't get a choice and variables have to be declared at the top.
Declare variables when you need them, that's usually when some intermediate result is ready or when you're just about to enter a loop.
So this does imply that error checks will often come before declarations.

Separating the operation method from the result

I more than once saw code of the form:
DiceThrower dt = new DiceThrower();
dt.throw(); //this is a void method
int result = dt.getResult();
instead of
DiceThrower dt = new DiceThrower();
int result = dt.throw();
My question is...why? Isn't it better to have the throw method returning the result? By not doing so, I could even incurr in sometimes forgetting about calling throw() before getResult(), accessing always old values of getResult(). Having both the operation and the result in the same method would circumvent that.
What is your oppinion on the matter?
Thanks
I'd use this pattern if you would need to use the data often, and it's expensive to (re)generate. But then memoization would probably be better, so the caller doesn't have to care.
You could even support both. Throw could return the value but it would also be available via getResult(). As noted above, if it's expensive to throw you want to cache the value in case it's needed more than once.

How can I unset an (unsigned) integer in ActionScript/Flex 3?

I have a class which is called a number of times. When the application goes to the next stage these all have to be unloaded. Because of that, I created an unload() method in the class.
The problem is that I can't seem to set my uint variable "charId" to null in order to "unset" it. The "delete" command is not possible either as that is only applicable for dynamic variables or something in that kind of way.
Now I wonder, how am I supposed to unset this variable, so it's memory will be re-allocated later on?
The class's unload method:
public function unload():void
{
trace("Unloading character with charname '" + charName + "'.");
enterButton.removeEventListener(MouseEvent.CLICK, enterClicked);
removeChild(enterButton);
enterButton = null;
charName = null;
charId = null; //this is possible but not recommended - what's a better way?
lobbyInterface = null;
}
So yeah, it's practically possible as it changes the variable type - however it's not recommended and raising a warning. So, what's a better way to do it?
Note that this object is also unloaded in it's parent. Does that also free all these variables from memory?
uint, int, Number and Boolean are not nullable in AS3. Number can be NaN, but that is really the best you can get. int and uint are always just 32 bit, so you can't stuff a null-reference in there.
The type of cleanup you are trying to do cannot be accomplished since AS3 has the concept of sealed classes. A sealed class has a fixed size in memory. When it comes to instance variables, think of it as a C struct, you can only dump all of it, or nothing. You can do anything in C of course, it's a fixed block in memory, an entity of one reference per variable.
What you want to do is only work with dynamic variables, which are maintained differently.
You don't need to do this sort of cleanup since Flash has garbage collection like most runtimes nowadays. It also deals with nested and circular references, the only thing you have to be sure about is, that you delete any "outer" references to that class. Things that are generally not collected are objects on the display list, running timers and intervals, and I/O related stuff. As soon as you have a reference chain from there to your object, it will not be collected.
Let us say you have an object A with an event handler for a mouse movement on an object on some list, referencing an object B. B will not be collected, but as soon as there is no chain leading to an object, it will be collected (sooner or later, the GC is quite lazy. But the more memory you use, the more it does its work).