Data in Javascript Object Performance - javascript

The more proficient I become with javascript, the more performance aware I want to be. For example, I had autocomplete box that would hit the server every so often to try auto-complete the users request. Exactly how google and most websites are enhancing their search. Now my question is if I am querying the FB api for a list of friends and storing these in a javascript object ( +- 700 with their full name and userid), how will this effect performance? I cant imagine it would be worse than constantly hitting the server for the request. Storing this info locally and then querying seems much more proficient. Where do I draw the line in storing information in a javascript object. I would like my server to as little as possible and have adopted the philopsophy on letting the client do 80% of the work and the server the remaining 20%. Obviously I want the client to experience a smooth application. How do the js ninjas test the performance of their application?

The most efficient solution - in terms of reduced network latency - would be to retrieve the friend list, store it using something like the localStorage API, and update the list in the background every once in a while. Keeping a list of this size in memory really shouldn't affect page performance much if at all (although on mobile this may not be the case). If someone has thousands of friends then you may see a slow-down, especially when reading the data from localStorage, but still, I doubt it.
Deciding where to draw the line is harder; it depends on so many factors. TBH this is something you may only know once your product is released and your users can give you feedback on performance, allowing you to fine-tune. A/B testing can help a lot in this regard.

Related

Measuring performance of clients

I'm currently researching any ways to gather some analytics/metrics on the performance of client machines to our webapp. The app is heavily ajax and we are hoping to gather some stats about how well the clients machines are running it.
We don't necessarily want to put performance monitoring code all through the application (for a great number of reasons this may not be feasible anyways). Rather we would like to be able to run some kind of test or something when a user submits feedback that could give us an idea of how well their browser/computer performs.
This has been a slightly tricky thing to research as it keeps bringing up discussions about profiling etc. This is obviously useful but only to a point as our development machines are massively overpowered. We are hoping to get some metrics on the kinds of machines our clients are connecting with.
Does any kind of library/framework or best practice exist for this? So far my best though is to run some kind of CPU intensive process through JS for a few seconds and measure the performance that way ...
Thoughts or suggestions? May be an interesting discussion.
here is what we do to monitor and analyze client usage data...
use Google Analytics to capture information about user (platforms, browsers, connection speeds, site usage, etc)
use Google Webmaster Tools to get additional site stats and optimization suggestions
use Pagespeed plugin to analyze/fine tune high volume and/or slow pages
use Apache AB or JMeter - to run basic load tests against high volume pages
This is an interesting question as you brought up most developer profile on their machines. I am not sure if there is any other way other than putting performance profiler in your code. The interesting part that you brought up that this is based on the user's feedback and not necessarily be sent all the time to the server.
We could develop a Profiler javascript class that basically collects:
Function name
Network round trip time
Total Function execution time
UserMachineProcessingTime = Total function execution time-network round trip
Other useful info (similar to what YSlow or similar tools provides)
As you mention that his is based on the user feedback, we don't need to send this information all the time as each function gets called (which makes the app very chatty). We then aggregate this information on the client's side and possibly store it somewhere (maybe using HTML5 local storage?)
Only when the user give their consent to submit the performance profile, then we send this information to the server where you get the needed data. It would be interesting too to see how the user's react if we how a tiny message saying "We notice that your performance is below our average users' performance. Would you like to send your performance profile so we could learn and make it better?" (Different wording necessary, I am bad with this, but that is basically the message). Upon saying yes, the Profile send out the aggregate information that it has collected + additional information that Javascript could collect (user agent, etc). Off course the question is how many users would opt in to send their profile info, but it is one approach that we could try.

Opinions on possible optimization for a web application using javascript

I'm thinking of implementing my web application in a certain way as an optimization, and I'd like to get people's opinions on whether this is a good idea or not.
Here's the details:
For most of my pages, instead of determining server side whether the user is logged in, and then modifying the page I send based on that, I want to send the same page to everyone, this way I can make use of my reverse caching proxy and for most requests not even have to run any dynamic code at all.
The differences that need to be done for logged in users will be done in javascript. The necessary information to make the changes (what their user name is, their user id, and if they are logged in or not) will be stored in a cookie that can be read by javascript.
I don't need to worry about the users not having javascript because my web app requires javascript to be used anyways.
Only the most popular pages that are accessible to both logged in and logged out users will do this.
What do you guys think? Pros/cons? Is this something that websites commonly do?
Doing it for 100% of your application would be a little problematic, however, it sounds like you are seeking to use something called the Model-View-Presenter pattern:
http://en.wikipedia.org/wiki/Model_View_Presenter
Be wary that, when using javascript, your code is exposed, meaning that any security measure taken is potentially hackable through the browser. Add protection on the server side and you are set.
Also, since you are going to rely heavily on javascript, I really recommend you using Mootools, which is an object-oriented approach to javascript. That way you can keep your code really modular, work around messy implementations using custom and class events, etc.
Major con: If you are determining what content a viewer can access with JavaScript alone, it stands to reason that a malicious user can potentially access premium content with just a little glance at your source code.
I'm not sure what you are optimizing really - you need to fetch the user data anyway, and only the server has that. Do you plan on sending an AJAX request requesting for data and using javascript to format it? you are only saving on output generation which is usually not the bottleneck in web application. Much more often the database / IO (files) / network (HTTP requests) are the bottlenecks.
The major con here is that by moving all output generation to javascript, you will increase substantially the download size and reduce overall responsiveness. Since none of the big sites use this approach, you can be sure it doesn't solve scalability problems.

severside processing vs client side processing + ajax?

looking for some general advice and/or thoughts...
i'm creating what i think to be more of a web application then web page, because i intend it to be like a gmail app where you would leave the page open all day long while getting updates "pushed" to the page (for the interested i'm using the comet programming technique). i've never created a web page before that was so rich in ajax and javascript (i am now a huge fan of jquery). because of this, time and time again when i'm implementing a new feature that requires a dynamic change in the UI that the server needs to know about, i am faced with the same question:
1) should i do all the processing on the client in javascript and post back as little as possible via ajax
or
2) should i post a request to the server via ajax, have the server do all the processing and then send back the new html. then on the ajax response i do a simple assignment with the new HTML
i have been inclined to always follow #1. this web app i imagine may get pretty chatty with all the ajax requests. my thought is minimize as much as possible the size of the requests and responses, and rely on the continuously improving javascript engines to do as much of the processing and UI updates as possible. i've discovered with jquery i can do so much on the client side that i wouldn't have been able to do very easily before. my javascript code is actually much bigger and more complex than my serverside code. there are also simple calulcations i need to perform and i've pushed that on the client side, too.
i guess the main question i have is, should we ALWAYS strive for client side processing over server side processing whenever possible? i 've always felt the less the server has to handle the better for scalability/performance. let the power of the client's processor do all the hard work (if possible).
thoughts?
There are several considerations when deciding if new HTML fragments created by an ajax request should be constructed on the server or client side. Some things to consider:
Performance. The work your server has to do is what you should be concerned with. By doing more of the processing on the client side, you reduce the amount of work the server does, and speed things up. If the server can send a small bit of JSON instead of giant HTML fragment, for example, it'd be much more efficient to let the client do it. In situations where it's a small amount of data being sent either way, the difference is probably negligible.
Readability. The disadvantage to generating markup in your JavaScript is that it's much harder to read and maintain the code. Embedding HTML in quoted strings is nasty to look at in a text editor with syntax coloring set to JavaScript and makes for more difficult editing.
Separation of data, presentation, and behavior. Along the lines of readability, having HTML fragments in your JavaScript doesn't make much sense for code organization. HTML templates should handle the markup and JavaScript should be left alone to handle the behavior of your application. The contents of an HTML fragment being inserted into a page is not relevant to your JavaScript code, just the fact that it's being inserted, where, and when.
I tend to lean more toward returning HTML fragments from the server when dealing with ajax responses, for the readability and code organization reasons I mention above. Of course, it all depends on how your application works, how processing intensive the ajax responses are, and how much traffic the app is getting. If the server is having to do significant work in generating these responses and is causing a bottleneck, then it may be more important to push the work to the client and forego other considerations.
I'm currently working on a pretty computationally-heavy application right now and I'm rendering almost all of it on the client-side. I don't know exactly what your application is going to be doing (more details would be great), but I'd say your application could probably do the same. Just make sure all of your security- and database-related code lies on the server-side, because not doing so will open security holes in your application. Here are some general guidelines that I follow:
Don't ever rely on the user having a super-fast browser or computer. Some people are using Internet Explore 7 on old machines, and if it's too slow for them, you're going to lose a lot of potential customers. Test on as many different browsers and machines as possible.
Any time you have some code that could potentially slow down or freeze the browser momentarily, show a feedback mechanism (in most cases a simple "Loading" message will do) to tell the user that something is indeed going on, and the browser didn't just randomly freeze.
Try to load as much as you can during initialization and cache everything. In my application, I'm doing something similar to Gmail: show a loading bar, load up everything that the application will ever need, and then give the user a smooth experience from there on out. Yes, they're going to have to potentially wait a couple seconds for it to load, but after that there should be no problems.
Minimize DOM manipulation. Raw number-crunching JavaScript performance might be "fast enough", but access to the DOM is still slow. Avoid creating and destroying elements; instead simply hide them if you don't need them at the moment.
I recently ran into the same problem and decided to go with browser side processing, everything worked great in FF and IE8 and IE8 in 7 mode, but then... our client, using Internet Explorer 7 ran into problems, the application would freeze up and a script timeout box would appear, I had put too much work into the solution to throw it away so I ended up spending an hour or so optimizing the script and adding setTimeout wherever possible.
My suggestions?
If possible, keep non-critical calculations client side.
To keep data transfers low, use JSON and let the client side sort out the HTML.
Test your script using the lowest common denominator.
If needed use the profiling feature in FireBug. Corollary: use the uncompressed (development) version of jQuery.
I agree with you. Push as much as possible to users, but not too much. If your app slows or even worse crashes their browser you loose.
My advice is to actually test how you application acts when turned on for all day. Check that there are no memory leaks. Check that there isn't a ajax request created every half of second after working with application for a while (timers in JS can be a pain sometime).
Apart from that never perform user input validation with javascript. Always duplicate it on server.
Edit
Use jquery live binding. It will save you a lot of time when rebinding generated content and will make your architecture more clear. Sadly when I was developing with jQuery it wasn't available yet; we used other tools with same effect.
In past I also had a problem when one page part generation using ajax depends on other part generation. Generating first part first and second part second will make your page slower as expected. Plan this in front. Develop a pages so that they already have all content when opened.
Also (regarding simple pages too), keep number of referenced files on one server low. Join javascript and css libraries into one file on server side. Keep images on separate host, better separate hosts (creating just a third level domain will do too). Though this is worth it only on production; it will make development process more difficult.
Of course it depends on the data, but a majority of the time if you can push it client side, do. Make the client do more of the processing and use less bandwidth. (Again this depends on the data, you can get into cases that you have to send more data across to do it client side).
Some stuff like security checks should always be done on the server. If you have a computation that takes a lot of data and produces less data, also put it on the server.
Incidentally, did you know you could run Javascript on the server side, rendering templates and hitting databases? Check out the CommonJS ecosystem.
There could also be cross-browser support issues. If you're using a cross-browser, client-side library (eg JQuery) and it can handle all the processing you need then you can let the library take care of it. Generating cross-browser HTML server-side can be harder (tends to be more manual), depending on the complexity of the markup.
this is possible, but with the heavy intial page load && heavy use of caching. take gmail as an example
On initial page load, it downloads most of the js files it needed to run. And most of all cached.
dont over use of images and graphics.
Load all the data need to show in intial load and along with the subsequent predictable user data. in gmail & latest yahoo mail the inbox is not only populated with the single mail conversation body, It loads first few full email messages in advance at the time of pageload. secret of high resposiveness comes with the cost (gmail asks to load the light version if the bandwidth is low.i bet most of us have experienced ).
follow KISS principle. means keep ur desgin simple.
And never try to render the whole page using javascript in any case, you cannot predict all your endusers using the high config systems or high bandwidth systems.
Its smart to split the workload between your server and client.
If you think in the future you might want to create an API for your application (communicating with iPhone or android apps, letting other sites integrate with yours,) your would have to duplicate a bunch of code for all those devices if you go with a bare-bones server implementation of your application.

How much external data is too much? (XML or JSON)

I have written pure JavaScript front ends before and started noticing performance decrease when working with large stores of data. I have tried using xml and json, but in both cases, it was a lot for the browser to handle.
That poses my question, which is how much is too much?
You can't know, not exactly and not always. You can make a good guess.
It depends on the browser, OS, RAM, CPU, what else is running at that moment, how fast their connection is, what else they're transferring, etc.
Figure out several situations you expect for your average user, and test those. Add for various best, worst, and interesting (e.g. mobile, tablet) cases.
You can, of course, apply experience and extrapolate from your specific cases, and the answer will change for the future.
But don't fall into the trap of "it works for me!"
I commonly see this with screen resolutions: as those have increased, it's much more popular to have multiple windows visible at the same time. In 1995 it was rare for me to not have something maximized; now fifteen years later, it's exactly the opposite.
Yet sometimes people will design some software or a website, use lower contrast[1], maximize it, and connect to a server on localhost—and that's the only evaluation they do.
[1] Because they know what the text says and don't need to read it themselves, so lower contrast looks aesthetically better.
In my opinion, if you need to stop and think about this issue, then the data is too much. In general you should design your applications so that users with a low-end netbooks and/or slow internet connections are still able to run them. Also keep in my mind that more often than not your application isn't the only page your users are visiting at the same time.
My recommendation is to use Firefox with Firebug to do some measurements. See how long a request takes to complete in a modest configuration. If it takes noticeable time for the browser to render data, then you'd better off doing a redesign.
A good guiding principle should be that instead of worrying about whether the browser can handle the volume of data you're sending it, worry about whether your user can handle it. It all depends on the presentation of course (i.e., a lot of data bound for a visualization tool that'll render a complex graph in a canvas is different than a lot of raw numbers bound for a gigantic table), but in my experience a user's brain reaches data overload before the browser/network/client computer.
It really depends on the form that your external data is going to take in your Javascript. If you want to load all your data at once and keep it in memory as a large object with lots of properties (associative array), then you will find that most current desktops can only handle about 100k entries (with small key-value pairs) before performance really degrades.
If it is possible, you should see if there are ways to only load the data that is needed by the user for a given request / interaction. You can use AJAX to request needed data and prefetch data that you think the user may need.

To Ajaxify Or Not?

I really love the way Ajax makes a web app perform more like a desktop app, but I'm worried about the hits on a high volume site. I'm developing a database app right now that's intranet based, that no more then 2-4 people are going to be accessing at one time. I'm Ajaxing the hell out of it, but it got me to wondering, how much Ajax is too much?
At what point does the volume of hits, outweigh the benefits seen by using Ajax? It doesn't really seem like it would, versus a whole page refresh, since you are, in theory, only updating the parts that need updating.
I'm curious if any of you have used Ajax on high volume sites and in what capacity did you use it? Does it create scaling issues?
On my current project, we do use Ajax and we have had scaling problems. Since my current project is a J2EE site that does timekeeping for the employees of a large urban city, we've found that it's best if the browser side can cache data that won't change for the duration of a user session. Fortunately we're moving to a model where we have a single admin process the timekeeping for as many employees as possible. This would be akin to how an ERP application might work (or an email application). Consequently our business need is that the browser-side can hold a lot of data, but we don't expect the volume of hits to be a serious problem. So we've kept an XML data island on the browser-side. In addition, we load data only on an as-needed basis.
I highly recommend the book Ajax Design Patterns or their site.
Ajax should help your bandwidth on a high volume site if that is your concern as you are, like you said, only updating the parts that need updating. My problem with Ajax is that your site can be rendered useless if the visitors do not have javascript enabled, and most of the time I do not feel like coding the site again for non-javascript users.
Look at it this way: AJAX must not be the only option because of the possibility of !script, it must exist as a layer on top of an existing architecture to provide a superior experience in some regards. Given that, it is impossible for AJAX to create more requests or more work than simple HTML because it is handling the exact same data transfer.
Where it can save you bandwidth and server load is because AJAX provides you the ability to transfer only the data. You can save on redundant HTML, image, css, etc requests with every page refresh whilst providing a snappier user experience.
As mike nvck points out the technique of polling is a big exception to this rule, but that's about the technique not the tech: you would have the same kind of impact if you had a simple page poll.
Understand the tool and use it for what it was designed. If AJAX implementation is reducing performance, you've done something wrong.
(fwiw, my experience of profiling AJAX vs simple HTML tends to result in ~60% bandwidth, ~80-90% performance benefits)
The most common scaling issue of ajax apps is when they are to set up to check back with the server to see if the content got updated in the meantime without the need for user actively requesting it. 5 clients checking every 10 seconds is not 5000 clients checking every 10 sec.
Ajax on one side reduces the server workload because it usually shows or refreshes just part of the page, while on the other side it increases number of hits to the server. I would say that all then depends of the architecture of your web application. If your application needs a lot of processing for every hit (like database access) regardless of size of the response, then Ajax will hit you a lot.

Categories

Resources