Is As3 const initialized during compile or runtime? - actionscript-3

I'm using ActionScript and I saw there is the possibility of using const attribues.
I'm with a doubt:
Is As3 const attributes initialized during compile or runtime?

Ok, let's spill some light on the flow of things with constants. I devised a pretty simple and self-explanatory class:
package
{
import flash.display.Sprite;
public class Kunst extends Sprite
{
public const A:int = int(trace("Init A:", A, B, C, D)) + 10;
public const B:String = initB() + String(trace("Init B:", A, B, C, D)) + initB();
public const C:int = 10 + 10;
static public const D:String = String(trace("Init D:", D, E, F)) + initD();
static public const E:Boolean = initE() && Boolean(trace("Init E:", D, E, F)) || initE();
static public const F:int = 10 + 10 + 10;
public function Kunst()
{
super();
trace("Check ABC:", A, B, C);
trace("Check DEF:", D, E, F);
}
private function initB():String
{
trace("Init B2:", A, B, C, D);
return "B";
}
static private function initD():String
{
trace("Init D2:", D, E, F);
return "D";
}
static private function initE():Boolean
{
trace("Init E2:", D, E, F);
return true;
}
}
}
It outputs the following:
Init D: null false 30
Init D2: null false 30
Init E2: undefinedD false 30
Init E: undefinedD false 30
Init E2: undefinedD false 30
Init A: 0 null 20 undefinedD
Init B2: 10 null 20 undefinedD
Init B: 10 null 20 undefinedD
Init B2: 10 null 20 undefinedD
Check ABC: 10 BundefinedB 20
Check DEF: undefinedD true 30
Lets comprehend the results:
All static constants go before the very first line of the application code executes. Before non-static constants of the main document class as well. That all was expected.
Among the same ones (i.e. either static or non-static) first initialize those that can be calculated right away, ones with outright value or simple formula. They, actually, could even be defined at the compile time.
The rest, the ones within the same (static or non-static) group, go by the exact order they are declared.
I thought you can initialize constants in the constructor block, but it turns out you can not. Maybe it was so in AS2, I don't really remember now.
At the moment the constructor starts executing, all the class member constants are already initialized.

Related

How to get thrust::pair first and second use javacpp

From https://github.com/bytedeco/javacpp/wiki/Interface-Thrust-and-CUDA, I write thrust java code. Struct field is public by default, but I use first() method to get the first field value of thrust::pair, error happen.
error: expression preceding parentheses of apparent call must have (pointer-to-) function type
error: macro "offsetof" passed 3 arguments, but takes just 2
{ sizeof(thrust::pair), offsetof(thrust::pair, first) },
So how to get thrust::pair first and second value ?
#Platform(include="<thrust/pair.h>")
#Namespace("thrust")
public class Thrust {
static { Loader.load(); }
#Name("pair<int, double>")
public static class Pair extends Pointer {
static { Loader.load(); }
public Pair(IntPointer key, DoublePointer value){
allocate(key, value);
}
private native void allocate(#ByRef IntPointer k, #ByRef DoublePointer v);
// will happen error: expression preceding parentheses of apparent call must have (pointer-to-) function type
public native IntPointer first();
// will happen error: macro "offsetof" passed 3 arguments, but takes just 2
{ sizeof(thrust::pair<int, double>), offsetof(thrust::pair<int, double>, first) },
public native Pair first(IntPointer p);
}
public static void main(String[] args) {
IntPointer i = new IntPointer(1);
i.put(10);
DoublePointer d = new DoublePointer(1);
d.put(10.0);
Pair p = new Pair(i, d);
System.out.println(p.first());
}
}

boost shared_memory_object use of deleted function

use of deleted function in class operator=
old version worked with old compiler but not with new versions
I need this "operator=" overloading for container operation.
#include <boost/interprocess/ipc/message_queue.hpp>
#include <iostream>
using namespace boost::interprocess;
class X {
public:
size_t m_len;
shared_memory_object m_shm;
const char* m_ptr;
X():
m_len(0),
m_shm(shared_memory_object()),
m_ptr(nullptr){}
X(size_t t, const char* n):
m_len(t),
m_shm(shared_memory_object()),
m_ptr(nullptr){
shared_memory_object::remove(n);
m_shm = shared_memory_object(open_or_create,n, read_write);
m_shm.truncate (m_len);
mapped_region region(m_shm, read_write);
m_ptr = static_cast<char*>(region.get_address());
}
X(const X&& x){
m_len = x.m_len;
m_shm = x.m_shm; //error use deleted function
m_ptr = x.m_ptr;
}
virtual ~X(){}
X& operator = (const X&& a) {
if(&a == this) return *this;
m_len = a.m_len;
m_ptr = a.m_ptr;
m_shm = a.m_shm; //error use deleted function
return (*this);
}
const char* get_name(){
return m_shm.get_name();
}
};
int main ()
{
X a = X(22, "test");
X b = a; //Error
return 0;
};
The above class will be used in std::vector and operator= is needed.
boost shared_memory_object has member:
shared_memory_object(shared_memory_object &&);
shared_memory_object& operator=(shared_memory_object &&);
Move operations can only work on non-const objects. Why? Because it steals resources from the source instance, then it must be non-const to be modifiable. So your move operations should take non-const objects:
now should be
----------------------------------------------------------
X(const X&& x) ==> X(X&& x)
X& operator = (const X&& a) { ==> X& operator = (X&& a) {
Named variable is treated as L-value, it implies copy operations are called. You need to use std::move to cast source to R-value reference, then move operations can be called:
m_shm = std::move(x.m_shm); // in move ctor
m_shm = std::move(a.m_shm); // in move assignment operator
and finally to call move ctor:
X b = std::move(a);

Naming convention of mutable/immutable methods

What is the naming convention when you have two generic-name methods performing the same operation, while one is immutable and the other is mutable?
EXAMPLE
Consider cellwise operation accepting 2 arrays of numbers: immutable version creates a new array to put the result in, while the mutable version stores the result in first array parameter.
Since the method name is something generic like apply as operation strategy (add, sub, mul, div) is specified by third argument, you can not use common words like add for mutability (a = a + 1) and plus for immutability (c = a + b).
CODE (TO BE SKIPPED)
Following details might be offtopic, but for illustration about what method I'm talking about:
#FunctionalInterface
public interface BinaryOperation { double apply(double a, double b); }
public final class BinaryOperations {
private BinaryOperations() {}
public static final BinaryOperation ADD = (a, b) -> a + b;
public static final BinaryOperation SUB = (a, b) -> a - b;
public static final BinaryOperation MUL = (a, b) -> a * b;
public static final BinaryOperation DIV = (a, b) -> a / b;
}
public final class DoubleArraysMath {
private DoubleArrayMath() {}
// ---> METHOD NAME OF INTEREST
public static void applyAsMutable(double[] a, double[] b, BinaryOperation o) {
apply(a, a, b, o);
}
// ---> METHOD NAME OF INTEREST
public static double[] applyAsImmutable(double[] a, double[] b, BinaryOperation o) {
double[] c = new double[a.length];
return apply(c, a, b, o);
return c;
}
private static void apply(double[] result, double[] a, double[] b, BinaryOperation o) {
for (int i = 0; i < a.length; i++) { result[i] = o.apply(a[i], b[i]); }
}
}
// just an example of usage
double[] r = DoubleArraysMath.applyAsImmutable(a, b, BinaryOperations.MUL);
DoubleArraysMath.applyAsMutable(a, b, BinaryOperations.ADD);
DoubleArraysMath.applyAsMutable(a, b, (ai, bi) -> ai*ai + bi); // some custom operation
SEPARATE CLASSES
Having mutable and immutable methods separated in DoubleArraysMutableMath and DoubleArraysImmutableMath classes avoids writting of "mutable/immutable" prefix/suffix at the begining/end of each method name. Following this pattern, you will end up with any utility class named as "mutable/immutable" (whether it is good or not I will leave as an open question).
SINGLE CLASS PROBLEM
In case we want to have these methods in single class (better maintenance), what is the proper naming "pattern"? Pattern I have used in my code sample "asMutable/asImmutable" or generally "mutable/immutable" might be incompatible with longer method names. Is there any other options?
Edit based on the comments
You should definitely implement mutable and immutable classes separately. Method names can be similar or different, it doesn't matter as interfaces will be different anyway.
Single class
Mutability strategy can be mentioned as an additional argument of the method, for example:
apply(a,b,Operation.ADD, ResultValue.NEW)
apply(a,b,Operation.ADD, ResultValue.FIRST_ARG)
apply(a,b,Operation.ADD, ResultValue.SECOND_ARG)
However, using multiple strategies in a single method will make the method confusing for the clients and error-prone.
If the signature of the method is
double [] apply(double[] arg1, double[] arg2, BinaryOperation)
then mutability or immutability can be part of the BinaryOperation itself:
public class FirstArgMutablePlusOperation {
double[] apply(double[] arg1, double[] arg2) {
//sample mutation
arg1[0] = arg1[0] + arg2[0];
// still return arg1 as a result
return arg1;
}
}
public class SecondArgMutablePlusOperation {
double[] apply(double[] arg1, double[] arg2) {
//sample mutation
arg2[0] = arg1[0] + arg2[0];
// still return arg2 as a result
return arg2;
}
}
public class ImmutablePlusOperation {
double[] apply(double[] arg1, double[] arg2) {
//sample mutation
double[] result = new double[arg1.length];
result[0] = arg1[0] + arg2[0];
return result;
}
}
Then a user can call apply method with correct strategy:
apply(arg1, arg2, new FirstArgMutablePlusOperation());
apply(arg1, arg2, new SecondArgMutablePlusOperation());
double[] result = apply(arg1, arg2, new ImmutablePlusOperation());
Immutable/mutable strategy can be a part of the BinaryOperation.
However, I rather avoid this solution as it will introduce if statements and a bulky implementation:
public enum ResultStrategy
{ RESULT, FIRST_ARG, SECOND_ARG };
public class PlusOperation extends BinaryOperation {
private final ResultStrategy strategy;
public PlusOperation(final ResultStrategy strategy) {
this.strategy = strategy
}
double[] apply(double[] arg1, double[] arg2) {
if(strategy == ResultStrategy.FIRST_ARG) {
//sample mutation
arg1[0] = arg1[0] + arg2[0];
// still return arg1 as a result
return arg1;
} else if(strategy == ResultStrategy.SECOND_ARG) {
//sample mutation
arg2[0] = arg1[0] + arg2[0];
// still return arg2 as a result
return arg2;
} else if(strategy == ResultStrategy.RESULT) {
double[] result = new double[arg1.length];
result[0] = arg1[0] + arg2[0];
return result;
}
}
}
Usage:
apply(arg1, arg2, new PlusOperation(ResultStrategy.FIRST_ARG));
apply(arg1, arg2, new PlusOperation(ResultStrategy.SECOND_ARG));
double[] result = apply(arg1, arg2, new PlusOperation(ResultStrategy.RESULT));
UPDATE
According to sample code provided in question
public enum ResultStrategy { FIRST_ARG, NEW_RESULT;} // SECOND_ARG = apply(b, a)
public class DoubleArraysMath {
...
public static double[] apply(ResultStrategy rs, double[] a, double[] b, BinaryOperation o) {
if (rs == ResultStrategy.FIRST_ARG) { return apply(a, a, b, o); }
return apply(new double[a.length], a, b, o);
}
}

How to adress elements of a recursive function?

Take a recursive function, say:
public static long rekurs(long n) {
if (n == 0) {
return 1;
} else if (n == 1) {
return 1;
} else {
return rekurs(n - 1)*(rekurs(n - 2)+4;
}
}
When n=20, the function has to find all the values S(n) for n=2,...,19 first.
When I let n go from 20 to 21, it does the same thing again (plus finding S(20)).
Now I want to create an array, in which the found values S(n) for n=2,...,19 are filled into, so that the function for n=21 does not have to do the same thing again, but how do I get those elements?
This is the solution I figured out, it's a little bit different from the lecture example.
The keyword that helped me is "dynamic programming".
import java.util.Arrays;
public class Bsp13 {
public static final int N = 0;
public static final int Ende = 20;
public static long[] schroe = new long[N + Ende + 1];
public static void main(String[] args) {
schroe[0] = 1;
schroe[1] = 1;
for (int n = 2; n <= Ende + N; n++) {
schroe[n] = ((6 * n - 3) * (schroe[n-1]) - (n - 2) * (schroe[n-2])) / (n + 1);
}
System.out.println(schroe[N]);
System.out.println(Arrays.toString(schroe));
System.out.println(schroe[N+Ende]);
}
}
What you are trying to do is called dynamic programming. Basically it is bookkeeping in order to not compute subsolutions more than once.
So basically, you need a mapping of n values to solution values. I would suggest you use a dictionary-like-datastructure for this task.
When a value for n needs to be computed, you first check whether the solution is in the dictionary, if yes you return the result. If not, you compute the result and put it into the dictionary.
Think about how you would initialize this dictionary and how you would pass it down to the recursive function calls.
Here's a lecture video on dynamic programming where the computation of Fibonnaci-numbers using dynamic programming is explained, which is very similar to what you are trying to do:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/lecture-videos/lecture-19-dynamic-programming-i-fibonacci-shortest-paths/

AS3: Optimizing Object Memory Size

I have have a class that I wrote, and it seems bigger than it should be. It doesn't extend anything, and has very little going on - or so I thought - but each one is taking up just under 100k100 bytes ( thanks back2dos ). I guess that I don't have a very good understanding of what really affects how much memory an object takes up in AS3.
If anyone can point me to some reading on the subject that might be helpful, or perhaps explain some insight into how to think about this, that would be awesome.
I would like to keep a LOT of these objects in memory - and I thought I could until now, but at this size I'm going to have to create them or use an object pooling technique of some kind.
Thanks for the assistance.
Edit: Although I've got this in order, I'm keeping the code I posted here for completeness. The class has been heavily modified from the original version. Values that were referencing other files have been made static as to allow the code to run for someone else ( in theory hehehe... ).
Although my situation is sorted out, I'll give the answer to a good reference for information on classes and memory.
In this case the class has 15 variables. I'm only using a single String and a bunch of ints, Numbers, and Booleans with some references to more of the same in globally available XML data. It also imports Point for the constructor, though no points are stored. In testing, even without the global XML references or Point class it's still around a ~84k each. There are getters for 7 of the variables and a couple methods in addition to the constructor. All of which are less than 20 lines ( and I have a very sparse coding style ).
The class mentioned for reference, but feel free to generalize:
package
{
public class AObject
{
private var _counter:int;
private var _frames:int;
private var _speed:int;
private var _currentState:String;
private var _currentFrame:int;
private var _offset:int;
private var _endFrame:int;
private var _type:int;
private var _object:int;
private var _state:int;
private var _x:Number;
private var _y:Number;
private var _w:int;
private var _h:int;
private var _update:Boolean;
public function AObject( targetX : int, targetY : int, state : int, object : int, type : int )
{
_x = targetX;
_y = targetY;
_type = type;
_object = object;
_state = state;
_counter = 0;
_w = 32;
_h = 32
_update = true;
setState( state );
}
public function setState( state:int ) : void
{
_currentState = "bob";
var frameCounter : int = 0;
var stateCounter : int = state - 1;
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
_offset = frameCounter;
_currentFrame = _offset;
_speed = 10;
_frames = 4;
_endFrame = _offset + _frames - 1;
}
public function get state() : int
{
return _state;
}
public function animate() : Boolean
{
if ( count() )
{
if( _currentFrame < _endFrame )
{
++_currentFrame;
}
else
{
_currentFrame = _offset;
}
_speed = 10;
return true;
}
else
{
return false;
}
}
private var adder: Number = 0;
private function count():Boolean
{
_counter++;
if ( _counter == _speed )
{
_counter = 0;
return true;
}
else
{
return false;
}
}
public function get x():int
{
return _x;
}
public function get y():int
{
return _y;
}
public function get type():int
{
return _type;
}
public function get object():int
{
return _object;
}
public function get currentFrame():int
{
return _currentFrame;
}
public function get w():int
{
return _w;
}
public function get h():int
{
return _h;
}
}
}
i am amazed, this compiles at all ... when i try to compile it with the flex SDK, it creates an enormous collision with the built-in class Object, which is the base class of any class, making my trace output overflow ...
other than that, this is an infinite loop if you pass a value for state bigger than 0
while ( state > 0 )
{
frameCounter += 4;
--stateCounter;
}
but it seems really strange these objects are so big ... after renaming and taking care not to pass in 0 for the state, i ran a test:
package {
import flash.display.Sprite;
import flash.sampler.getSize;
import flash.system.System;
public class Main extends Sprite {
public function Main():void {
const count:int = 100000;
var start:uint = System.totalMemory;
var a:Array = [];
for (var i:int = 0; i < count; i++) {
a.push(new MyObject(1, 2, 0, 4, 5));
}
var mem:uint = System.totalMemory - start - getSize(a);
trace("total of "+mem+" B for "+count+" objects, aprox. avg. size per object: "+(mem/count));
}
}
}
it yields:
total of 10982744 B for 100000 objects, aprox. avg. size per object: 109.82744
so that's quite ok ... i think the actual size should be 4 (for the bool) + 4 * 11 (for the ints) + 4 (for the reference to the string) + 8 * 3 (for the three floats (you have the adder somewhere over the count) + 8 for an empty class (reference to the traits objects + something else), giving you a total of 88 bytes ... which is, what you get, if you getSize the object ... please note however, that getSize will only give you the size of the object itself (as calculated here) ignoring the size of what strings or other objects your object references ...
so yeah, apart from that name you definitely should change, the problem must be somewhere else ...
greetz
back2dos
If you really want to save on space, you can fake shorts by using unsigned integers, and using upper/lower bits for one thing or another.
ints are 4 bytes by nature, you can reuse that int on anything less than 2^8.
width height
0xFFFF + 0xFFFF
offset endframe
0xFFFF + 0xFFFF
This though gets ugly when you want to write anything or read anything, as to write width or height you'd have to:
writing:
size = (width & 0x0000FFFF) << 16 | (height & 0x0000FFFF);
reading:
get width():uint { return (size & 0xFFFF0000) >> 16 };
That's ugly. Since you're using getters anyways, and assuming computation speed is not an issue, you could use internal byte arrays which could give you even more granularity for how you want to store your information. Assuming your strings are more than 4 bytes, makes more sense to use a number rather than a string.
Also, I believe you will actually get some memory increase by declaring the class as final, as I believe final functions get placed into the traits object, rather than