Polymertemplate instantiation time - polymer

I'm using a library that in its main class extends PolymerTemplate where I noticed that the creation of an instance of the component in the library takes about 20ms.
I've removed basically everything from that class and the corresponding .js files to end up with the simplest possible component... basically a div with no content. And still to create this mi
long startTime = System.currentTimeMillis();
Autosuggest<String> autosuggest1 = new Autosuggest<>();
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("ExecutionTime: " + elapsedTime + " ms");
My guess now is, that it takes that long to create the dependency on PolymerTemplate. Is there a way to speed up this creation process? Or maybe defer it to a later stage?
I'd simply need to speed up the loading of a formular that has several of those components in it.
Update 09/09/2021:
I've updated the libray in question from PolymerTemplate to LitTemplate. Still a bit slow, but at least future proof. In case there is a sampler to test it as well.

Related

Caffeine Cache - How to get information of creation date of an element

Is there any way to access the creation timestamp of an element from the CaffeineCache?
Kind of cache.get("x").getTimestamp()?
The cache tries to store the minimal metadata required to perform its operations, so some conveniences are left out to avoid waste. In those cases you should consider adding that metadata by wrapping your value.
The cache does expose runtime metadata, but this often depends on how it was constructed. That can be accessed by using Cache.policy(). For example cache.policy().expireAfterWrite() offers an ageOf(key) method to determine how long the entry has resided since its expiration timestamp was last reset. To calculate how much time until the entry expires, you could subtract the age from the policy's duration (via getExpiresAfter()).
Cache interface provides getPolicy method to inspect and perform low-level operations based on the cache's runtime characteristics. For example below snippet return the age of an entry in the cache using after write policy.
private static void printAgeOfEntryUsingAfterWritePolicy(Cache cache, Object key) {
Optional<FixedExpiration> expirationPolicy = cache.policy().expireAfterWrite();
if (!expirationPolicy.isPresent()) {
return;
}
Optional<Duration> ageOfEntry = expirationPolicy.get().ageOf(key);
if (!ageOfEntry.isPresent()) {
return;
}
Duration duration = ageOfEntry.get();
System.out.println("Element with key " + key + " is in the cache from " + duration.getSeconds() + " seconds....");
}
Reference link.

Actionscript 3 - How to access integer variable in main timeline from inside MovieClip

First, sorry if my english is bad and I'm new to Actionscript 3.
I have a movieclip, I give it an instance name "symbol1" which include a code inside it, like this :
var a: int = 2;
var b: int = 3;
var total: int = a + b;
How can I access the "total" integer variable inside that movieclip in the main timeline? I try to trace it but the result is 0. In the main timeline I wrote this code :
trace(symbol1.total);
I appreciate the help, thanks
The "problem" is the order of execution of frames. The parent is executed first.
The value is 0 and not undefined because the property does indeed exist since the creation of the object which happens in a previous separate step.
You should be able to verify that by stepping through your code with the debugger.
I've made 6 games. each game is in the MovieClip including the game functions, times, scores, variables, etc. I want the total score of each game summed outside each MoviClips, which is in the main timeline. is there a solution to that problem?
This makes your timing problem even more apparent.
You arrive at a frame, which contains a game and you immediately want to access the total score of it. It should be obvious that the game first has to be played in order to obtain a score from it.
Asking a newborn baby what his favourite moment in the first 60 years of his live was doesn't make much sense.
You have to notify the main timeline that the game was finished. The best way to do this is to dispatch an Event from the game. Frames are totally unnecessary.
Your code could look something like this:
var game:Game = new Tetris();
addChild(game);
game.addEventListener(GameEvent.FINISH, onFinish);
function onFinish(e:GameEvent):void
{
trace("finished game with score " + game.score);
}
If you want to update the exterior score sum while the game is running (to immediately reflect any change in the score, not just when the game is finished), your best bet is to create a ScoreModel for the score which you pass to the game, the Game. The Game modifies the ScoreModel, which in turn causes it to dispatch Events:
var score:ScoreModel = new ScoreModel();
var game:Game = new Tetris(score);
addChild(game);
score.addEventListener(Event.CHANGE, onScoreChange);
function onScoreChange(e:Event):void
{
trace("score changed to " + score);
}
Both examples are "what your code could look like"-type of examples. There are many questions about how to dispatch events that explain how to do this in more detail.
Something that came up in the comments from #Jezzamon:
I'm pretty sure you're accessing the variable total correctly, otherwise I would expect it to cause an error (you can test this by trying to run trace(symbol1.variableNameThatDoesntExist)).
No, there cannot be an error for accessing a variable as seen in the question. The reason for that is that the property is accessed on a MovieClip object, which is a dynamic class. As such, the compiler doesn't know if accessing a particular property is valid, because that can change at runtime. And because nothing else relies on the value to be valid, there isn't a runtime error either.
Here's some example code to illustrate this:
trace("toString: " + {}.toString); //toString: function Function() {}
trace("bananas: " + {}.bananas); //bananas: undefined
This is one of the reasons why using MovieClip can be a bad idea. In addition to that, the Flash IDE modifies the code behind the scenes. That can lead to unexpected execution of code. A purely code based workflow sure is advantageous in this regard and recommended.

Actionscript 3.0 Point Object not picked up by Garbage Collection

I have just been trying to fix a few memory leaks in my project and have discovered an interesting problem. It seems like a vast majority of my 'Point' objects are not being picked up by the Garbage Collector. Each frame it creates about 5000 new Point objects and less than 10% of them seem to ever get picked up. Even when you use code like this:
var tempPoint :Point = new Point();
tempPoint = null;
Even if I repeat it over 500 times, only a tiny fraction seem to be erased. This is really stating to get on my nerves now and I was wondering if anyone has encountered this before, knows how to solve it / get around it, or cares to enlighten me on what exactly I am doing wrong.
Would love to know anyone's thoughts on this
ps. I am using The Miner to check the resource usage
Edit: Have now done a quick check where I had the program running for about an hour and although the memory usage went up about 140MB it did start garbage collecting at this point and did not go past that. So they will be picked up but not until you have several million created ;)
How long are you waiting for them to be erased?
If you are creating 5000 new objects per frame, it's probably a good idea to use an object pool.
class PointPool {
private var _points:Vector.<Point>;
public function PointPool() {
_points = new Vector.<Point>();
}
public function createPoint(x:Number, y:Number):Point {
var p:Point = null;
if( _points.length > 0 )
p = _points.pop();
else
p = new Point();
p.x = x;
p.y = y;
return p;
}
public function returnPoint(point:Point):void {
_points.push(point);
}
}
Just a thought :)
I will quote Grant Skinner to answer your question:
A very important thing to understand about the Garbage Collector in FP9 is that it’s operations are deferred. Your objects will not be removed immediately when all active references are deleted, instead they will be removed at some indeterminate time in the future (from a developer standpoint).
[...]
It’s very important to remember that you have no control over when your objects will be deallocated, so you must make them as inert as possible when you are finished with them.
So, what's happened with your code? FP created something near 5000 instances of Point. If you look the memory usage over time you may notice that it will drop to the initial value after a few seconds.
The best way to avoid this behaviour is to pool the created objects and reuse them instead of creating a new one.

Actionscript 3.0 getter setter increment

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.

AS3: Calculating the current upload speed (or throughput)

I am uploading files using the upload() method of the FileReference class. I want to display the current connection speed and I was wondering what was a good way to do that.
My current technique is to use a Timer every 1 mili second such as follows:
var speed:Function = function(event:TimerEvent):void {
speed = Math.round((currentBytes - lastBytes) / 1024);
lastBytes = currentBytes;
}
var speedTimer:Timer = new Timer(1000);
speedTimer.addEventListener(TimerEvent.TIMER, uploadSpeed);
and currentBytes gets set into the ProgressEvent.PROGRESS. This technique seems imprecise. I was wondering what other ways I could use to calculate the upload speed while uploading and display it in real time.
Any ideas or opinions are welcomed!
Thank you very much,
Rudy
If that code block is a copy and paste it certainly won't work as you have expected it to. You declare speed as a function within which you appear to redefine it as a number. I appreciate the Flash IDE let's you get away with sketchy grammar, but code like that is going to lead you into all kinds of trouble. Try to be explicit when writing your code.
Try something like this, replacing yourLoader with whatever identifier you assigned to the uploader:
private var speed:Number = 0;
private var lastBytes:uint = 0;
private function uploadSpeed(event:TimerEvent):void
{
speed = Math.round((yourLoader.currentBytes - lastBytes) / 1024);
lastBytes = yourLoader.currentBytes;
}
private var speedTimer:Timer = new Timer(1000);
speedTimer.addEventListener(TimerEvent.TIMER, uploadSpeed);
That should calculate how many bytes moved in 1 second intervals.
Edit:
You might like to make the interval a little smaller than 1000ms and calculate an average speed for your last n samples. That would make the number your users see appear more stable than it probably does right now. Make speed an Array and .push() the latest sample. Use .shift() to drop the oldest samples so that you don't lose too much accuracy. Trial and error will give you a better idea of how many samples to hold and how often to take them.
You can moniter the upload speed on the server and then send that data back to the client. This technique is often used for ajax file upload forms.