AS3: Perform action in intervals based on incrementing int - actionscript-3

So as not to complicate my question, I won't involve the context, but basically let's say I have a variable:
var foo:int;
And 'foo' is constantly incrementing, how would I be able to perform a function every 300 increments (300,600,900, etc) of 'foo'?
Cheers
EDIT: Also worth mentioning, the number can occasionally skip numbers as it is a rounded version of a decimal number that is incrementing

What about making it a private variable and only acces it using these accessor methods:
function getFoo():int {
return foo;
}
function setFoo(newFoo:int):void {
if (newFoo % 300 > foo % 300) performAction();
foo = newFoo;
}
You could also add convenience methods like incrementFoo(increment:int) of course.
Sorry for possible syntax errors. I haven't used AS3 for quite a while.

Related

How can I display multiple return values of a recursive function efficiently?

I will be using JavaScript to demonstrate my example, but the question remains open to other programming languages as well.
Let's consider a simple recursive function:
function f(x){
if(x>1) return f(x-1)+5;
else return 3;
}
Let's say I want to display the value of the function for all x from 1 to 5, where x is an integer. The most obvious solution would be the following:
for(i=1; i<=5; i++){
console.log(f(i));
}
This method, however, seems incredibly inefficient, as we are calling the function 5+4+3+2+1 times. Intuitively, only 5 function calls would be necessary, as whenever we want the value of f(5), it is necessary to find the value of f(4) f(3) f(2) and f(1) first, so after finding f(5), we wouldn't need to call f(4) and start the entire process all over again to just to find the value of f(4) which we already found once.
Any ideas?

Optimizing/reducing pure functions with same in/out types to combine them in a simpler pure function?

Disclaimer: I have almost no mathematics notions, so this question could be very basic for some of you.
I'm searching for the name of a concept which consists in combining pure functions together (say, functions with the same input and output types and number of parameters) to make them simpler.
Suppose I have these 3 methods with the same signature:
addOne(param: number): number {
return param + 1;
}
addTwo(param: number): number {
return param + 2;
}
multiplyByThree(param: number): number {
return param * 3;
}
Now I know that I'll always use these functions in the same order and same param.
Ex: I will process a sound or an image.
I want to avoid uselessly applying coefficient or offsets that could be computed together (optimization/regression).
Let's say I have this imaginary library with a method called computeOptimizedFunction that applies this concept to my functions. It takes any number of functions with the same signature as input.
var optimized = computeOptimizedFunction(addOne, addTwo, multiplyByThree);
Actually equals to:
var optimized = (param: number) => 3 * (param + 3);
Anyone here has an idea of how this concept or pattern is called, if it exists?

Is the stack limit of 5287 in AS3 variable or predefined?

I ran a test just now:
function overflow(stack:int = 0):void
{
if(stack < 5290)
{
trace(stack);
overflow(stack + 1);
}
}
overflow();
This always throws a StackOverflow error after 5287 calls.
Error #1023: Stack overflow occurred.
Is this limit variable (depending on machine specs, environment, etc) or is that a flat value defined somewhere? If I change the if statement to less than 5287, I don't get the error.
Obviously it's variable. Since all the calculations you really do are located in stack (disassembly report codes show pushbyte instructions and other stuff that's working with stack, as non-operand arithmetics), this value only reports how many function contexts can be put into the stack until it overflows.
I have decided to run some tests for recursion thresholds as based on this article that was referenced in baris's comment. The results were pretty embarrassing. Test environment: FlashDevelop 3.3.4 RTM, Flash player debugger 10.1.53.64, flash compile mode: release. "Debug" mode didn't change numbers cardinally, checked that too.
Locals number Iterations (static int) Iterations (Math.random())
0 5306
1 4864 4856
2 4850 4471
3 4474 4149
4 4153 3870
5 3871 3868
6 3869 3621
7 3620 3404
8 3403 3217
9 3210 3214
10 3214 3042
11 3042 3045
10 mixed 3042 1 value was assigned Math.random() and 9 - static int
10 advancedRandom 2890 1 value was assigned a custom random with 1 parameter
Note, all of these values vary within a margin of ten between subsequent executions. The "static int" and "Math.random()" are designations of what is assigned to locals wihin the recursively called function. This, however, leads me to assume the following:
Including function calls into the recursive function adds to function context
Memory for locals is assigned along with its type, in chunks of more than 8 bytes, because adding a local does not always decrease recursion limit
Adding more than one call to a certain function does not add more memory to function context
The "memory chunk" is most likely 16 bytes long, because this value is 2^N, an addition of one int or Number local does not always decrease recursion, and this is more than 8, as a raw value of a Number variable takes 8 bytes, being a double-precision floating-point.
Assuming #4 is correct, the best value for function context size appeared to be 172 bytes, with total stack size being 912632 bytes. This largely confirms my initial assumption that the stack size is actually 1 megabyte in Flash 10. Flash 11 showed me a bit higher numbers when I have tried opening the test SWF in its debugger, but I didn't make extensive tests with it.
Hm, this is interesting. I took a look at the link that Barış gave. It seems like it might be to be with 'method complexity' after all, but I am not sure how to further test it. I am using Flash CS5, publishing for Flash Player 10, Actionscript 3 (of course).
Original:
function overflow(stack:int = 0):void {
if(stack < 5290){
trace(stack);
overflow(stack + 1);
}
}
// gives 5287
Now adding a single Math.random() call to the overflow() method:
function overflow(stack:int = 0):void {
Math.random();
if(stack < 5290){
trace(stack);
overflow(stack + 1);
}
}
// gives 4837
Adding multiple Math.random() calls make no difference, nor does storing it in a local variable or adding another parameter to the overflow() method to 'carry' that random generated value
function overflow(stack:int = 0):void {
Math.random();
Math.random();
if(stack < 5290){
trace(stack);
overflow(stack + 1);
}
}
// still gives 4837
At this point I tried different Math calls, such as:
// just the change to that 1 line:
Math.pow() // gives 4457
Math.random(), Math.sqrt(), Math.tan(), Math.log() // gives 4837
Interestingly, it doesn't seem to matter what you pass in to the Math class, but it remains constant:
Math.sqrt(5) vs Math.sqrt(Math.random()) // gives 4837
Math.tan(5) vs Math.tan(Math.random()) // gives 4837
Math.pow(5, 7) vs Math.pow(Math.random(), Math.random()) // 4457
Until I chained 3 of them:
Math.tan(Math.log(Math.random())); // gives 4457
It looks like two Math calls from that 'group' is "equal" to one Math.pow() call? =b Mixing Math.pow() and something else doesn't seem to decrease the value though:
Math.pow(Math.random(), Math.random()); // gives 4457
However, chaining two Math.pow()'s:
Math.pow(Math.pow(Math.random(), Math.random()), Math.random()); // 4133
I could go on and on, but I wonder if there is some pattern:
Results: 5287, 4837, 4457, 4133
Differences: 450 380 324
Musst be variable! Just compiled your sample and i get to 5274 before stack overflow.
#baris thats for the mxmlc compiler
+1 for stack overflow question ^^

Faster way to tell if a sprite is near another sprite?

When one of my sprites is being dragged (moved around), I'm cycling through other sprites on the canvas, checking whether they are in range, and if they are, I set a background glow on them. Here is how I'm doing it now:
//Sprite is made somewhere else
public var circle:Sprite;
//Array of 25 sprites
public var sprites:Array;
public function init():void {
circle.addEventListener(MouseEvent.MOUSE_DOWN, startDrag);
}
private function startDrag(event:MouseEvent):void {
stage.addEventListener(MouseEvent.MOUSE_MOVE, glowNearbySprites);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrag);
circle.startDrag();
}
private function stopDrag(event:MouseEvent):void {
stage.removeEventListener(MouseEvent.MOUSE_MOVE, glowNearbySprites);
stage.removeEventListener(MouseEvent.MOUSE_UP, stopDrag);
circle.stopDrag();
}
private function glowNearbySprites(event:MouseEvent):void {
for (var i = 0; i < sprites.length; i++) {
var tSprite = sprites.getItemAt(i) as Sprite;
if (Math.abs(tSprite.x - circle.x) < 30 &&
Math.abs(tSprite.y - circle.y) < 30) {
tSprite.filters = [new GlowFilter(0xFFFFFF)];
}
else {
tSprite.filters = null;
}
}
}
Basically I'm cycling through each sprite every time a MOUSE_MOVE event is triggered. This works fine, but the lag when dragging the sprite around is pretty noticeable. Is there a way to do this that is more efficient, with no or less lag?
Well, depending on the size of the amount of sprites you have, it may be trivial. However, if you're dealing with over 1k sprites -- use a data structure to help you reduce the amount of checks. Look at this QuadTree Demo
Basically you have to create indexes for all the sprites, so that you're not checking against ALL of them. Since your threshold is 30, when a sprite moves, you could place it into a row/column index of int(x / 30), int(y / 30). Then you can check just the sprites that exist in 9 columns around the row/column index of the mouse position.
While this would seem more cumbersome, it actually it way more efficient if you have more items -- the number of checks stays consistent even as you add more sprites. With this method I'm assuming you could run 10k sprites without any hiccup.
Other performance optimizations would be:
use an vector/array of sprites rather than getChildAt
preincrement i (++i)
store a static single instance glowfilter, so it's only one array, rather creating a separate filter for all the sprites.
GlowFilter is pretty CPU intensive. Might make sense to draw all the sprites together in one shot, and then apply GlowFilter once to it -- (this of course depends on how you have things set up -- might even be more cumbersome to blit your own bitmap).
Make your variable declaration var sprite:Sprite = .... If you're not hard typing it, it has to do the "filters" variable lookup by string, and not by the much faster getlex opcode.
I'd incorporate all the improvements that The_asMan suggested. Additionally, this line:
tSprite.filters = [new GlowFilter(0xFFFFFF)];
is probably really bad, since you're just creating the same GlowFilter over and over again, and creating new objects is always expensive (and you're doing this in a for loop every time a mouse_move fires!). Instead create it once when you create this class and assign it to a variable:
var whiteGlow:GlowFilter = new GlowFilter(0xFFFFFF);
...
tSprite.filters = [whiteGlow];
If you're still having performance issues after this, consider only checking half (or even less) of the objects every time you call glowNearbySprites (set some type of flag that will let it know where to continue on the next call (first half of array or second half). You probably won't notice any difference visually, and you should be able to almost double performance.
Attempting to compile the suggestions by others into a solution based on your original code, so far I've created the GlowFilter only once and re-used, secondly I've changed the loop to use a for each instead of the iterant based loop, third I've updated to use ENTER_FRAME event instead of MOUSE_MOVE. The only thing I've left out that's been suggested so far that I see is using a Vector, my knowledge there is pretty much nil so I'm not going to suggest it or attempt until I do some self education. Another Edit
Just changed the declaration of sprites to type Vector no code here for how it's populated but article below says you can basically treat like an Array as it has all the same method implemented but has a couple of caveats you should be aware of, namely that you cannot have empty spots in a Vector and so if that is a possibility you have to declare it with a size. Given it knows the type of the object this probably gets a performance gain from being able to compute the exact position of any element in the array in constant time (sizeOfObject*index + baseOffset = offset of item). The exact performance implications aren't entirely clear but it would seem this will always result in at least as good as Array times if not better.
http://www.mikechambers.com/blog/2008/08/19/using-vectors-in-actionscript-3-and-flash-player-10/
//Array of 25 sprites
public var sprites:Vector.<Sprite>;
private var theGlowFilterArray:Array;
public function init():void
{
theGlowFilterArray = [new GlowFilter(0xFFFFFF)];
circle.addEventListener(MouseEvent.MOUSE_DOWN, startDrag);
}
private function startDrag(event:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrag);
addEventListener(Event.ENTER_FRAME, glowNearbySprites);
circle.startDrag();
}
private function stopDrag(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stopDrag);
removeEventListener(Event.ENTER_FRAME, glowNearbySprites);
circle.stopDrag();
}
private function glowNearbySprites(event:Event):void
{
var circleX:Number = circle.x;
var circleY:Number = circle.y;
for each(var tSprite:Sprite in sprites) {
if (Math.abs(tSprite.x - circleX) < 30 && Math.abs(tSprite.y - circleY) < 30)
tSprite.filters = theGlowFilterArray;
else
tSprite.filters = null;
}
}
You problem is that making calculations that are at least linear O(n) on every mouse change event is terribly inefficient.
One simple heuristic to bring down the amount of times that you make your calculations is to save the distance to the closest sprite and only after mouse moved that distance would you recalculate the potential crash. This can be calculated in constant time O(1).
Notice that this works only when one sprite moves at a time.

Javascript - Arguments Vs Nested functions Vs Performance

Javascript noob question - which one of the following is best practice and performance friendly, also welcome any other suggestions too. This is simplest version of original project. There will be 20+ variables and 10+ inner functions (Ex: 'process' in the case).
The advantage of Method 1 is it doesn't need to send arguments to the functions but as it nests all the functions inside the main function (possibly regenerate all the inner function for each instance of Foo). While the method 2 is free from function nesting but requires lot of arguments. Note that also there will be multiple instance of Foo constructor.
Method 1:
function Foo () {
var a = 1;
var b = 2;
var c = (a+b)/2;
var $element = $('#myElement');
var process = function (){
var x = a+b+c;
$element.css('left', x)
return x;
}
x = process ();
}
Method 2:
function Foo () {
var a = 1;
var b = 2;
var c = (a+b)/2;
var $element = $('#myElement');
x = process (a, b, c, $element);
}
function process (a, b, c, $element){
$element.css('left', x)
return x;
}
The separated functions are definitely the way to go for performance. While there are situations where the variable scoping of nested functions would be nice to have, the performance hit can be huge if the function is large.
Keep in mind that every time Foo if called, var process is reallocating all the memory for the new function that is being created, rather than keeping the function in memory and just passing it new parameters. If the function is big, this is going to be a pretty intense task for the Javascript interpreter.
Here are some hard numbers that may help as well (Contains performance comparisons and actual benchmarks that you can run in your own browser): http://jsperf.com/nested-functions-speed, http://jsperf.com/nested-named-functions/5
Actually browsers do optimize even nested functions to where performance differences compared to functions declared in outer scope become negligible.
I blogged my findings and created a performance test to support this claim.
EDIT: The test was broken, after fixing the test shows that it's still faster not to nest functions.