how upgrade perf and minimize main thread work next/Dynamic - reactjs

I got optimization question about SEO & Performance, as a lot of us I'm challenging my selft to have the best score on the lighthouse to have the best chance to raise in the google index. So I reduce a lot of my assets, use module.css but even if my score is over 95 on desktop my mobile score is only over 75/60 ​​points ...
I found to way to increase the performance, I noticed the request number is a bit to hight, 105 requests:
So it’s follows that’s following warning:
Which is impact the FCP and the LCP, So I look at about kind of solution to split the code and call it when the are required (lazy load). So next / Dynamic from next should be the solution but I’m a bit confused because I don’t know exactly how to use it, I mean:
-What is the good case to import component with or without next / Dynamic?
-Will I get worse if I abuse of it?
-Should I use AMP?

Related

What are the alternative ways of Floodlight Counter tag(in Google Tag Manager)?

Here is the Story of current implementation:
I have over 50 Ad Campaigns. To track the user-behavior, I have implemented Floodlight Count tag for all of those. However, it is eating up lot of container size. Therefore, I am looking for a solution with which, I can dynamically fire Floodlights or without implementing Floodlights, I can get the similar result.
I already have implemented this solution. However, it increases the Loadtime of the webpage as it contains RegEx table(and my RegEx table has over 50 entries).
I am looking for a solution which involves minimal use of Custom variables by mostly using what is available by-default in GTM.
What's available by default in GTM (not counting custom variables) wouldn't be sufficient for covering 50 ad campaigns in an effective manner. You could always create 50 triggers and 50 tags, hardcoding your ids and maintain them separately in different tags, which is quite far from being the best practice. It actually may be the worst practice, especially given how the container size is hard-limited for GTM.
Even a large rLUT should be very insignificant given that the variable against which it's executed is reasonably small and the url is most definitely a tiny string. Have you actually measured the page load speed with and without the rLUT? Have you debugged the load speed issues and narrowed them down to the rLUT? It's actually quite an achievement to make GTM significantly affect the page load speed, given how it's all async and non-blocking.
You could reimplement the rLUT in a CSJ variable, which may be more preferable if you're good at JS, but it won't improve performance. Just like an rLUT won't hinder performance.

React error in render/flush: RangeError in flush RangeError: Maximum call stack size exceeded

I've been in the process of rewriting an old AngularJS app in React (actually it's using preact, chosen by the developer who started this project initially).
This app handles large deeply nested objects that get be displayed via Material UI accordions and tables. The data is more WIDE than deep, but at any rate, React has trouble rendering it all without this RangeError.
I've been dancing with this issue for a while now and have avoided it by strategically managing accordions and not rendering data for accordions that are not open.
I've commonly seen this reported as a recursion issue, and I've carefully reviewed the ode to confirm there is no recursion involved. Plenty of iteration, but no recursion.
Please note the stack trace, it's hitting this in the flush() function, which is not in our application code, but in the Chrome debugger VM. I've set breakpoints and it appears to be something related to DOM operations as the objects being flushed are React elements. Here's a code snippet from the point where this error is hit:
function flush(commit) {
const {
rootId,
unmountIds,
operations,
strings,
stats
} = commit;
if (unmountIds.length === 0 && operations.length === 0) return;
const msg = [rootId, ...flushTable(strings)];
if (unmountIds.length > 0) {
msg.push(MsgTypes.REMOVE_VNODE, unmountIds.length, ...unmountIds);
}
msg.push(...operations); <--- error occurs here when operations.length too long
And the stack trace logged when error occurs:
VM12639:1240 Uncaught (in promise) RangeError: Maximum call stack size exceeded
at flush (<anonymous>:1240:8)
at Object.onCommit (<anonymous>:3409:19)
at o._commit.o.__c (<anonymous>:3678:15)
at QRet.Y.options.__c (index.js:76:17)
at Y (index.js:265:23)
at component.js:141:3
at Array.some (<anonymous>)
at m (component.js:220:9)
The error is occurring if operations is too large. Normally it will be anywhere from a dozen or so in length up to maybe 3000, depending on what's going on, but when I try to load our page displaying the wide/deep nested object this number is more like 150000, which apparently is choking the spread operator.
My sense is that this type of app is a challenge for React. I cannot think of another example of a React app that displays data the way we do with this. If anyone here has experience with this sort of dataset and can offer suggestions as to how to make this work, please share.
My guess is I'm going to need to somehow break this object up into smaller chunks that represent smaller updates, but I'm posting here in case there's something I can learn.
It looks similar to this open issue on the React repo, only it happens in a different place (also in dev tools). Might be worth reporting your issue there too. So probably React is otherwise "fine" rendering this amount of elements, though you'll inevitably get slow performance.
Likely the app is just displaying too much data, or doing it inefficiently.
but when I try to load our page displaying the wide/deep nested object this number is more like 150000, ...
150000 DOM operations is a really high amount. Either your app really does display a whole lot of elements, or the old AngularJS app had too many wrapper elements and these were preserved. Since you mention it concerns data tables, it's probably the first reason. In any case complex applications always need some platform specific optimization.
If you can give an idea about the intended use case, or even better, share (parts of) the code, that would help others to give more targeted advice. Are the 150k operations close to what would happen in real world usage, or is it just a very inflated number for stress testing? Do you see any other performance regressions, compared to the Angular app, with very complex objects? How many tables are on the screen at a time?
A few hundreds of visible elements on the screen already gets quite cramped. So where would all these extra operations coming from? Either you're loading a super long page of which a user can only see a few percent at the same time, or the HTML structure is unnecessarily deeply nested.
Suggested performance improvements
I wouldn't say React isn't suitable for really large amounts of data, but you do need to watch out for some things yourself. React is only your vehicle to apply changes to the DOM. Putting a large amount of elements in the DOM is always going to lead to decreased performance, and is something you usually want to avoid.
In this case you could consider whether it's necessary to display all the table's data, which is probably the bulk of the operations. Using pagination would resolve the problem, and might even make it more user friendly.
If that's not an option, you maybe can use a library like react-lazyload to show/hide the items as they enter/exit the visible part of the table. To achieve this, use their unmountIfInvisible prop. You can then replace a complex data row with a single element that has the same height. The last is important to preserve the scroll height.
<LazyLoad
height={100}
offset={100}
unmountIfInvisible
placeholder={<tr height={100}/>}
>
<MyComplexDataRow />
</LazyLoad>
This way your data table never consists of much more complex elements than can be seen in the viewport. You probably need to tune the offset a bit so that it's always ready in time as it's benig scrolled.

Any examples of using a Wandsearcher in vespa ? (After a weighted set query)

Currently i am using the REST interface to query vespa, which seems to work great but something tells me that i should be using searchers in the application to make the client(server side code) a bit lighter (bundle the jar file in the application package) to make it a bit smoother. I have managed to do some simple searcher/processor applications. But this is a bit overwhelming.
So are there any readily available examples ?
Basicially i want to:
Send to /search?query=someId
Do a ordinary search for the weighted set on this documentID (I guess this one can be handy: https://docs.vespa.ai/documentation/reference/inspecting-structured-data.html)
Take those items in the response and add it to a wand item(s) and query for a wand with wandsearcher on a given field. Similar to the yql:
"select * from sources * where wand(interest, some weightedsets));","ranking":"combined_score" and return the matches.
Just curious also, apart from the trouble of string building with the http request i am doing at the moment are there any performance gains of using a searcher or go the java route vs rest?
thanks for any insight or code help i can start with.
There is an example of using the WandItem (YQL wand)here https://docs.vespa.ai/documentation/advanced-ranking.html and see also https://docs.vespa.ai/documentation/using-wand-with-vespa.html as there are two wand implementations available in Vespa, it sounds from the description that the wand() is what you want to use for this use case. For the first call you probably want to have a dedicated document summary to reduce the amount of data fetched for your first query and also the option of serving it out of memory only (See https://docs.vespa.ai/documentation/document-summaries.html)
Also see https://docs.vespa.ai/documentation/searcher-development.html as a general resource on writing searchers.
For your use case it makes a lot of sense to write a searcher to perform these two queries as your second query depends on the first and you avoid the cost of rendering/http/yql parsing which might matter if your client is remote with high network latency.

Building a NetHack bot: is Bayesian Analysis a good strategy?

A friend of mine is beginning to build a NetHack bot (a bot that plays the Roguelike game: NetHack). There is a very good working bot for the similar game Angband, but it works partially because of the ease in going back to the town and always being able to scum low levels to gain items.
In NetHack, the problem is much more difficult, because the game rewards ballsy experimentation and is built basically as 1,000 edge cases.
Recently I suggested using some kind of naive bayesian analysis, in very much the same way spam is created.
Basically the bot would at first build a corpus, by trying every possible action with every item or creature it finds and storing that information with, for instance, how close to a death, injury of negative effect it was. Over time it seems like you could generate a reasonably playable model.
Can anyone point us in the right direction of what a good start would be? Am I barking up the wrong tree or misunderstanding the idea of bayesian analysis?
Edit: My friend put up a github repo of his NetHack patch that allows python bindings. It's still in a pretty primitive state but if anyone's interested...
Although Bayesian analysis encompasses much more, the Naive Bayes algorithm well known from spam filters is based on one very fundamental assumption: all variables are essentially independent of each other. So for instance, in spam filtering each word is usually treated as a variable so this means assuming that if the email contains the word 'viagra', that knowledge does affect the probability that it will also contain the word 'medicine' (or 'foo' or 'spam' or anything else). The interesting thing is that this assumption is quite obviously false when it comes to natural language but still manages to produce reasonable results.
Now one way people sometimes get around the independence assumption is to define variables that are technically combinations of things (like searching for the token 'buy viagra'). That can work if you know specific cases to look for but in general, in a game environment, it means that you can't generally remember anything. So each time you have to move, perform an action, etc, its completely independent of anything else you've done so far. I would say for even the simplest games, this is a very inefficient way to go about learning the game.
I would suggest looking into using q-learning instead. Most of the examples you'll find are usually just simple games anyway (like learning to navigate a map while avoiding walls, traps, monsters, etc). Reinforcement learning is a type of online unsupervised learning that does really well in situations that can be modeled as an agent interacting with an environment, like a game (or robots). It does this trying to figure out what the optimal action is at each state in the environment (where each state can include as many variables as needed, much more than just 'where am i'). The trick then is maintain just enough state that helps the bot make good decisions without having a distinct point in your state 'space' for every possible combination of previous actions.
To put that in more concrete terms, if you were to build a chess bot you would probably have trouble if you tried to create a decision policy that made decisions based on all previous moves since the set of all possible combinations of chess moves grows really quickly. Even a simpler model of where every piece is on the board is still a very large state space so you have to find a way to simplify what you keep track of. But notice that you do get to keep track of some state so that your bot doesn't just keep trying to make a left term into a wall over and over again.
The wikipedia article is pretty jargon heavy but this tutorial does a much better job translating the concepts into real world examples.
The one catch is that you do need to be able to define rewards to provide as the positive 'reinforcement'. That is you need to be able to define the states that the bot is trying to get to, otherwise it will just continue forever.
There is precedent: the monstrous rog-o-matic program succeeded in playing rogue and even returned with the amulet of Yendor a few times. Unfortunately, rogue was only released an a binary, not source, so it has died (unless you can set up a 4.3BSD system on a MicroVAX), leaving rog-o-matic unable to play any of the clones. It just hangs cos they're not close enough emulations.
However, rog-o-matic is, I think, my favourite program of all time, not only because of what it achieved but because of the readability of the code and the comprehensible intelligence of its algorithms. It used "genetic inheritance": a new player would inherit a combination of preferences from a previous pair of successful players, with some random offset, then be pitted against the machine. More successful preferences would migrate up in the gene pool and less successful ones down.
The source can be hard to find these days, but searching "rogomatic" will set you on the path.
I doubt bayesian analysis will get you far because most of NetHack is highly contextual. There are very few actions which are always a bad idea; most are also life-savers in the "right" situation (an extreme example is eating a cockatrice: that's bad, unless you are starving and currently polymorphed into a stone-resistant monster, in which case eating the cockatrice is the right thing to do). Some of those "almost bad" actions are required to win the game (e.g. coming up the stairs on level 1, or deliberately falling in traps to reach Gehennom).
What you could try would be trying to do it at the "meta" level. Design the bot as choosing randomly among a variety of "elementary behaviors". Then try to measure how these bots fare. Then extract the combinations of behaviors which seem to promote survival; bayesian analysis could do that among a wide corpus of games along with their "success level". For instance, if there are behaviors "pick up daggers" and "avoid engaging monsters in melee", I would assume that analysis would show that those two behaviors fit well together: bots which pick daggers up without using them, and bots which try to throw missiles at monsters without gathering such missiles, will probably fare worse.
This somehow mimics what learning gamers often ask for in rec.games.roguelike.nethack. Most questions are similar to: "should I drink unknown potions to identify them ?" or "what level should be my character before going that deep in the dungeon ?". Answers to those questions heavily depend on what else the player is doing, and there is no good absolute answer.
A difficult point here is how to measure the success at survival. If you simply try to maximize the time spent before dying, then you will favor bots which never leave the first levels; those may live long but will never win the game. If you measure success by how deep the character goes before dying then the best bots will be archeologists (who start with a pick-axe) in a digging frenzy.
Apparently there are a good number of Nethack bots out there. Check out this listing:
In nethack unknown actions usually have a boolean effect -- either you gain or you loose. Bayesian networks base around "fuzzy logic" values -- an action may give a gain with a given probability. Hence, you don't need a bayesian network, just a list of "discovered effects" and wether they are good or bad.
No need to eat the Cockatrice again, is there?
All in all it depends how much "knowledge" you want to give the bot as starters. Do you want him to learn everything "the hard way", or will you feed him spoilers 'till he's stuffed?

How to type faster [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I've typed around 75wpm for the last few years but I've always wondered how people type +100wpm.
I've searched but I primarily find typing tutors that teach you to type.. not teach you to type faster. So far the only tip I've come across is to learn dvorak.
Are there exercises or tips to help break through the 75wpm wall?
I'm assuming Steve Yegge's recent post prompted this? The comments contain a number of tools and games for measurement and improvement, both online and off. I'll list them here:
Gnu Typist
TyperA
TypeRacer (Several people named this site)
Typespeed
typeonline.co.uk
Update: I just tried GNU Typist as per Mark Biek's suggestion, and I have to say that it seems like the best of the lot mentioned so far. It looks like there is a Windows version available, although I'm sure there are prettier (and more expensive) apps out there.
Setting yourself up in an ergonomic typing position is a good start. Take a look at the diagram here - notice the arms in a straight line, feet on the floor, etc.
In my experience most people tend to slow down when they get to unusual keys - numbers, symbols, punctuation, etc, so maybe some focused practice on those key combinations? practice typing out long strings of numbers and symbols, maybe try to use some Perl code as your copy-page :)
One of the things that helped me was something I learned from pianist... when doing a touch typing program, deliberately slow down and speed up your rate of typing from disgustingly slow to really fast in slow waves. This helps train yourself to figure out how to get your fingers to work together faster and reinforces the key locations.
Another one is perhaps a speed reading course might help? Generally your fingers are the last line of slow down in typing.
If you want to practice while having a little fun check out http://typeracer.com
It let's you compete against other people and trust me, there's nothing better to get you typing faster than normal than a little healthy competition.
Practice!
GNU Typist is a great, free, multi-platform program for practicing. They have different sets of exercises for practicing touch-typing as well as general Speed Drills.
Like a previous poster said, practice, practice, practice. But, if you are a developer (since you are on this site I assume that you are), then writing code will probably not be the type of practice that you need to improve your typing skills past your current maximum. I would even argue that 75wpm is more than adequate for any code writing task. But if you really want to practice more then I would recommend picking up a copy of Typing of the Dead
Consider switching to a keyboard layout that's designed for quick typing instead of just being layed out as it is for historical reasons, e.g. Dvorak or Colemak.
For me, it also helped a lot to use the caps lock key as backspace, for example using SharpKeys on Windows.
If you are really hardcore, create your own keyboard layout. On Windows, you can do that with the Microsoft Keyboard Layout Creator.
Chat. A lot.
I never received any touch-typing training. Infact, when i first started, i had to search the keyboard for the key... Now after 7 years of IMing, its all muscle memory. I have never tried to speed my typing, but a lot of times it just flows without me even realizing that i am typing as i think. Also i have noticed i can type in my usernames and phrases i often use a LOT faster than the other things.
This may or may not have been a useful answer.
Be careful, increasing your typing speed can increase the risk of carpal tunnel syndrome:
"The typing speed may affect risk, in some cases, however. For example, the fingers of typists whose speed is 60 words per minute exert up to 25 tons of pressure each day." [source]
Consistency and practice. Four things that improved my typing dramatically:
Find a comfortable keyboard that
fits your hands very well. It's less
about ergonomics or split keyboards,
but more about finding one with perfect finger reach. And this means using the keyboard for a couple weeks to see if it fits. Once you pick a keyboard, use it 100% of time. Have the same keyboard at home and work.
Make sure your workstation is
properly fitted to you. Basically, follow any decent ergonomics guide (90 degrees everywhere is WRONG!!!).
All of this "ergonomics" stuff has the benefit of stress on the rest
of your body that can distract you or cause muscle fatigue (i.e. slower typing). Again, use the same workstation configuration everywhere--if that means getting the same expensive chair at home, do it.
When emailing, chatting, and posting, use complete words and sentences. Abbreviations, slang, and other "shortcuts" taught me a lot of bad typing habits and made me lazy. They also had a lot of awkward letter combinations that didn't show up in other places, including normal composition and coding.
Consistency. Use the same tools with
the same settings and shortcuts all
the time. The less time you spend
worrying about how the software
works and reaching for the mouse,
the faster your typing will be.
You need to pick yourself up a copy of Typing of the Dead and start killing zombies. You'll be honing your typing skills and preparing for the eminent zombie apocalypse at the same time! Grab the demo to check it out!
In all seriousness, I've had this game for years and it really has helped me improve my typing skills and it's way more fun than any other typing program out there.
Type to the beat of a song. Start with a slow beat and work your way up. Don't rush it. Typing in bursts is often counter productive. Rhythm causes accuracy. The keyboard is just like a musical instrument and that's how musicians gain accuracy. You also need to practice regularly, even if just for 5 mins each day, to train your muscles.
I forget the details, but I remember the following was asked of some famous violinist:
"How did you learn to play so fast?"
His reply: "Really, really slowly".
:)
Use both hands (and all ten fingers).
To maximize your typing speed, you need to use the opposite pinky to shift/ctrl etc. and you want to minimize the amount of time you have to "reacquire" the home position. My biggest increase in typing when coding was to really learn my IDE's keyboard shortcuts, since that eliminated the relatively slow process of using the mouse.
Disable your mouse. (This is more for overall computer productivity than WPM.)
And I know you can't do it on your own, so get someone to enforce it.
It'll force you to learn keyboard shortcuts and consider keyboard-friendly options.
A nice, tactile keyboard helps. Especially if it's blank. You'll be speeding along in no time.
http://store.daskeyboard.net/prdaskeulorb.html
If you are having a problem with a particular key combo or miss-typing a particular word, or even just want to practice something, put it into your password. That way you get it fixed in your muscle memory as you can't even see what you are typing.
Practice, Practice and Practice
Make it so that you cannot see the keyboard, this will force your mind to remember where the keys are. I used this when starting on the Colemak keyboard layout and it worked really well.
The biggest way I increased my speed was by never looking down at the keyboard. I also have a very ergonomic keyboard that splits the keyboard in half so I get use to the right hand using the right side and the left hand using the left side.
My hands aren't my bottleneck, so touchtyping doesn't make me any faster. I already don't get enough bitrate out of my head to max out my hunt and peck. some people (me) may never be able to TT effectively.
agreed on muscle memory though. common thngs like usr/pass always get boshed out quickly without thinking, but for code, my hands are not the bottleneck
Get a Kinesis Essential keyboard. Keys are laid out better for faster typing.
IRC-ing a lot helpen a great deal with me;
Especially playing those Trivia like games where the fastest one gets the points.
You can also try "typespeed" on Linux.
If you really need more speed and you think you've mastered the technique you can also consider using the Dvorak keyboard layout; It will help you type fast but you really need to adapt to it.
I switched to Dvorak and my typing speed has increased, and I also learned after 8 years, how to touch type.
I would double the suggestion(s) to switch to an ergonomic typing position. Also, I've noticed that I cannot type faster on my laptop. I have an external anti-RSI QWERTY keyboard (with the reverse-V style key layout), and I can type a lot faster with more accuracy on that that I can on my laptop.
If you use a contoured keyboard, like, for instance, the Kinesis Advantage keyboard, it is easier to type blind, since it is much easier to feel where your hands are on the keyboard if it isn't flat. After a couple of days I was typing considerably faster than on a normal keyboard. And there is also a version switchable to Dvorak layout, though I never bothered to try that.
About blind typing: in my experience, knowing where your hands are is the important and difficult thing in blind typing - and after years of keyboard use you know very well where the common keys are. So just concentrating every once in a while to have your hands in the proper position for blind typing, and to type the keys with the right finger will get you into blind typing in a couple of months without any additional exercise.
(source: kinesis-ergo.com)

Resources