As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
background:
I've searched around for a reference, or possibly a tool, that helps you theoretically evaluate the efficiency (resource cost) of your JavaScript. This search has turned up a lot of excellent debugging software, but I can't really find something that helps me optimize the code, by utilizing less resource-intensive methods.
question:
Is there any resource (online guide, list, database, book, anything) or perhaps some software (web-based, browser plugin, IDE extension) that will help you optimize your JavaScript?
example:
innerText in IE / textContent in Firefox requires far fewer resources than innerHTML in either browser.
That one is kinda common sense, because it's less powerful, but there are other comparisons I hear about on a daily basis, and can't really verify if they are in fact better for optimized code or more efficient, and even if I could I have no way to test it!
Any ideas?
In the same line as strife25, firebug has a very handy method of measuring time without handling any dates. Just use this:
console.time("Your timer name");
//Execute some javascript
console.timeEnd("Your timer name");
Then, check the console.
alt text http://aquate.us/u/62232567893647972047.jpg
Edit -- off by 30 odd seconds. :(
the usual way to evaluate Javascript is by evaluating the amount of time it takes for a set of code to execute:
var begin = new Date().getTime();
//do stuff
console.debug( new Date().getTime() - begin );
However, there are some issues with this in IE. if a script takes <15ms to run, IE returns 0ms as the result.
Various javascript libraries have testing frameworks to help evaluate your code's speed. Dojo's testing framework is called DOH.
John Resig also made a firebug plugin called FireUnit which allows you to easily evaluate the time it takes for a function to execute, and with a little configuring, also outputs the Big O of a function, which is a great piece of data.
Check out Resig's video from JSConf on JS performance testing:
Measuring Javascript Performance - John Resig
FireUnit rundown
I always liked the simple approach with Firebug:
console.time("timer-name");
and
console.timeEnd("timer-name");
Good for granular level measurements.
Firebug's 'profile' tool is great for measuring javascript performance. It shows you all the bottlenecks in your code in a function by function breakdown, showing which one's had the highest average time, most calls, etc.
Profiler in IE8 is amazing. It gives you a tree view along with the Inclusive time (in ms)
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
It seems that the phrase "Premature Optimization" is the buzz-word of the day. For some reason, iphone programmers in particular seem to think of avoiding premature optimization as a pro-active goal, rather than the natural result of simply avoiding distraction. The problem is, the term is beginning to be applied more and more to cases that are completely inappropriate.
For example, I've seen a growing number of people say not to worry about the complexity of an algorithm, because that's premature optimization (eg Help sorting an NSArray across two properties (with NSSortDescriptor?)). Frankly, I think this is just laziness, and appalling to disciplined computer science.
But it has occurred to me that maybe considering the complexity and performance of algorithms is going the way of assembly loop unrolling, and other optimization techniques that are now considered unnecessary.
What do you think? Are we at the point now where deciding between an O(n^n) and O(n!) complexity algorithm is irrelevant? What about O(n) vs O(n*n)?
What do you consider "premature optimization"? What practical rules do you use to consciously or unconsciously avoid it?
EDIT
I know my description is a bit general, but I'm interested in specific, practical rules or best practices people use to avoid "pre-mature optimization", particularly on the iphone platform.
Answering this requires you to first answer the question of "what is pre-mature optimization?". Since that definition clearly varies so greatly, any meaningful answer requires the author to define the term. That's why I don't really think this is a CW question. Again, if people disagree, I'll change it.
What is premature optimization?
Premature optimization is the process of optimizing your code (usually for performance) before you know whether or not it is worthwhile to do so. An example of premature optimization is optimizing the code before you have profiled it to find out where the performance bottleneck is. An even more extreme example of premature optimization is optimizing before you have run your program and established that it is running too slowly.
Are we at the point now where deciding between an O(n^n) and O(n!) complexity algorithm is irrelevant? What about O(n) vs O(n*n)?
It depends on the size of n and how often your code will get called.
If n is always less than 5 then the asymptotic performance is irrelevant. In this case the size of the constants will matter more. A simple O(n * n) algorithm could beat a more complicated O(n log n) algorithm for small n. Or the measurable difference could be so small that it doesn't matter.
I still think that there are too many people that spend time optimizing the 90% of code that doesn't matter instead of the 10% that does. No-one cares if some code takes 10ms instead of 1ms if that code is hardly ever called. There are times when just doing something simple that works and moving on is a good choice, even though you know that the algorithmic complexity is not optimal.
Every hour you spend optimizing rarely called code is one hour less that you can spend on adding features people actually want.
My vote goes for most people optimize what they think is the weak point, but they don't profile.
So regardless of how well you know algorithms and regardless of how well you've written your code, you don't know what else is happening outside your module. What do the APIs you've called do behind the scenes? Can you always gaurantee that the particular order of ops is the fastest?
This is what is meant by Premature Optimization. Anything that you think is an optimization that has not been rigorously tested by way of a profiler or other definitive tool (clock cycles by ops is not a bad thing, but it only tells you performance characteristics ~ actual calls is more important than timing, usually), is a premature optimization.
#k_b says it well above me, and it's what I say too. Make it right, make it simple, then profile, then tweak. Repeat as necessary.
Order of priority: 1. It has to work
2. It has to be maintainable
3. It has to be machine-efficient
That was from the first week of my first programming course. In 1982.
"Premature optimization" is any time Priority 3 has been considered before Priority 1 or 2.
Note that modern programming techniques (abstractions and interfaces) are designed to make this prioritization easier.
The one gray area: during the initial design, you do have to check that your solutions are not inherently cripplingly slow. Otherwise, don't worry about performance until you at least have some working code.
For some people, optimization is part of the fun of writing code, premature or not. I like to optimize, and restrain myself for the sake of legibility. The advice not to optimize so much is for the people that like to optimize.
iphone programmers in particular seem
to think of avoiding premature
optimization as a pro-active goal
The majority of iPhone code is UI related. There is not much need to optimize. There is a need not to choose a poor design that will result in bad performance, but once you start coding up a good design there is little need for optimization. So in that context, avoiding optimization is a reasonable goal.
What do you consider "premature
optimization"? What practical rules do
you use to consciously or
unconsciously avoid it?
Using the Agile approach (rapid iterations with refinement of requirements through interactions with users) is helpful as the awareness that the current interface is probably going to change drastically after the next session with the users makes it easier to focus on developing the essential features of the application rather than the performance.
If not, a few iterations where you spent a lot of time optimizing a feature that was entirely discarded after the session with the user should give you the message.
Algorithm complexity, and even choice, is an issue that should be hidden behind an interface. For example, a List is an abstraction that can be implemented various ways with different efficiencies for different situations.
Sometimes avoiding premature optimization can aid design, because if you design with the idea that you will need to optimize later, then you are more inclined to develop at the abstract level (e.g. list) rather than the iimplementation (e.g. Array or linked list) level.
This can result in simpler, and more readable code, in addition to avoiding distraction. If programmed to the interface, different implementations can be swapped in later to optmize. Prematurely optimizing leads to the risk that implementation details may be prematurely exposed and coupled with other software components that should not see these details.
What practical rules do you use to
consciously or unconsciously avoid it?
One way to avoid unnecessary optimization is to consider the relative cost benefit:
A) Cost for programmer to optimize code + cost to test said optimization + cost of maintaining more complex code resulting from said optimization
vs.
B) Cost to upgrade server on which software runs or simply buy another one (if scalable)
If A >> B consider whether it's the right thing to do. [Ignoring for the moment the environmental cost of B which may or may not be a concern to your organization]
This applies more generally than just to premature optimization but it can help instill in your developers a sense that spending their time doing optimization work is a cost and should not be undertaken unless there is a real measurable difference in something that actually matters like: number of servers required or customer satisfaction through improved response times.
If management can't see the benefit in reduced $ and customers can't see the benefit in better response times, ask yourself why you are doing it.
I think this is a question of common sense. There's a need to understand the big picture, or even what's happening under the hood, to be able to consider when a so-called "premature" move is justified.
I've worked with solutions where web service calls were necessary to calculate new values based on the contents of a local list. The way this was implemented was by making a web request per value. It wouldn't be premature optimization to send several values at a time. The same thing goes for the use of database transactions for multiple operations, i.e. multiple inserts.
When it comes to algorithms, initially the most important thing is to get it right and as simple as possible. Worrying about stack vs heap issues at that point would be madness.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it good practice to start all JS files with a semi colon to account for any bad scripts included before it? Or don't bother?
Thanks
;(function(){ /* my script here */ })();
Do bother, more and more people leverage the power of ASI and write semicolonless JavaScript. In semicolonless JS world that's the "rule", you put a semicolon before raw expressions, like ;(), or ;[] or ;//, as well as after 'use strict'; and omit them everywhere else. Raw expressions are not very common, except the typical IIFE.
Even if you write JS with semicolons, that particular one is safe and will do more good than bad.
not a good idea:
hide errors
stuff wont work on your site with no clear indication as to why
see no reason to use faulty scripts.
Instead, start all your scripts with "use strict"; which on some browsers will check your scripts for some error-prone practices, and interestingly I believe it will have a similar effect as the ; for closing any outstanding statements from faulty scripts included prior.
The leading semicolon is actually pretty useful if you split and decouple a lot of code into several javascript files, which you at some point, concatenate to create a production file.
It will simply help to avoid errors in constructs like
(function() {
}())
if all your files are wrapped in constructs like this, it fill fail without any semicolon, separating them. Other than that, there isn't much value in that pattern.
I usually don't bother, but, if you want to be really safe, then do it. If you are using somebody else's library, I would probably do it, but, then again, it is your choice.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been thinking a lot about the way that jQuery is implemented in Javascript code. Libraries such as jQuery and Prototype bind to an alias by default; for these examples, they use the dollar sign $. (Underscore, appropriately, uses an underscore character _.)
I understand how this works. I also understand that many libraries provide a noConflict mode.
My question is, why do these libraries use an alias by default?
From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial. (Honestly - I'm a little biased, because I don't have issues typing long variable names.) I thought that maybe it was for filesize purposes, but with the proliferation of minifiers, it seems like it'd be a moot point (and a form of premature optimization).
On the flip side, the aliases seem to cause a lot of confusion for people using these libraries.
Now, I'm not really arguing against the use of aliases - I'm just wondering why it's the default option for these libraries. Currently, to avoid an alias, we explicitly have to declare that we don't want to use it. Are there specific benefits that I'm missing about the use of aliases for library calls? The only advantage that I could readily think of is if you somehow wrote cross-library code - to swap libraries, you simply swap the alias. I don't think I've ever seen this done, though.
Anyone know the reasoning behind this? I, for one, would really love to know.
"From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial."
That's what the people who designed VB thought too. "What's this
for (int i=0; i<10;i+=2){
}
Stuff! What's wrong with:
For i as Integer = 0 To 10 Step 2
Next i
So I save 13 keystrokes! That's trivial."
It's not trivial when this is what we do all. day. long.
Take the jQuery Cycle plugin: http://malsup.github.com/jquery.cycle.all.js. It has 400 instances of $. If you were to use jQuery instead of $, that would be an extra 2000 keystrokes. It's the reason why IDEs now perform autocomplete of parens, etc. etc. etc.
Using jQuery and Prototype together is not good idea. Ideally there must be only 1 javascript framework for the site, and a lot of calls to it. So the best (default) choice is to use shorthand alias for it's main function.
Anyway, if you need to use several libraries/frameworks together on the same page, and you want to avoid conflicts, you can use noConflict mode.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I made two games so far, one was a simple 2D MMO, and another one was a 2D portal clone with some more features.
Anyway, I noticed that my class design in those two games varied a bit:
In the MMO, I'd create a class called "Enemy", and this class would take some arguments such as image and attack_power.
In the Portal-like game, I'd create classes for every kind of object specifically, for example "Box" or "Wall" or "Doors". Then, these would take only position as an argument, and inside I'd flag them for movable, physics with true/false, and then I would have an update function which would act upon these objects.
What is the best approach to this kind of problem? How specific should I be, and should I use something completely different?
I made those games in Python and Javascript.
That depends on the purposes of each class, on the language which you're using, on what you're trying to achieve, the specific problems you're trying to solve, and a zillion other factors - every problem and every program is different.
I'd recommend doing some research around the SOLID prinicples of OO design, these principles are more like guidelines than rules, but understanding them and being able to apply them to a real problem might help you achieve 'good' class design - http://davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html
There is no "best" approach, since there are no universal right or wrong ways to solve a problem, and a perfect solution is not always possible or desirable when you factor in other real world issues which you might come across along the way.
The kinds of questions you might think about asking yourself could be along the lines of
What does my program actually do? Often, the most useful classes emerge when you start to think about the way your program works. For example, your movable Box class may end up doing very little to the point where it's easier to represent it as a simple struct, but you might find a use for a BoxMover class which is packed full of 'move' logic, and knows how to move Boxes around.
How do the different entities in my program behave? You don't mention very many details about your classes, so only you would know whether they do different things, but if you end up with dozens of almost-identical classes (particularly where the differences are restricted to data) then you may have gone too far.
What do I actually want to do with the classes? Its important to think about interfaces; the focus of OO design is more about the way your classes are used than the data which your classes store. (e.g. contrary to popular belief, a Square may have absolutely nothing in common with a Rectangle). Likewise, a class which has nothing more than single-line get-set functions for its interface is probably not making your life any easier, or bringing you any closer to finding a good solution.
What is the best approach to this kind of problem?
Some game developers would say that OOP is not the type of programming you would use for games. They would have a global data store, and use procedural code to access the global data store.
You're the only one who can really answer this question. Did your classes help or hinder your game programming?
How specific should I be, and should I use something completely different?
As specific as you need to be to model the game. In my opinion, since you finished the games, you had a good model. As you get more development experience, you'll have seen more models that you can use.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have been exploring different methods to clean up and test my JavaScript. I figured just like any other language one way to get better is to read good code. jQuery is very popular so it must have a certain degree of good coding.
So why when I run jQuery through JSLint's validation it gives me this message:
Error:
Problem at line 18 character 5:
Expected an identifier and instead saw
'undefined' (a reserved word).
undefined,
Problem at line 24 character 27:
Missing semicolon.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Expected an identifier and instead saw
'='.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Stopping, unable to continue. (0%
scanned).
This was done using JSLint and jquery-1.3.1.js
JSLint tests one particular person's (Douglas Crockford) opinions regarding what makes good JavaScript code. Crockford is very good, but some of his opinions are anal retentive at best, like the underscore rule, or the use of the increment/decrement operators.
Many of the issues being tagged by JSLint in the above output are issues that Crockford feels leads to difficult to maintain code, or they are things that he feels has led him to doing 'clever' things in the past that can be hard to maintain.
There are some things Crockford identifies as errors that I agree with though, like the missing semicolons thing. Dropping semicolons forces the browser to guess where to insert the end-of-statement token, and that can sometimes be dangerous (it's always slower). And several of those errors are related to JSLint not expecting or supporting multiple assignments like jQuery does on line 24.
If you've got a question about a JSLint error, e-mail Crockford, he's really good about replying, and with his reply, you'll at least know why JSLint was implemented that way.
Oh, and just because a library is popular doesn't mean it's code is any good. JQuery is popular because it's a relatively fast, easy to use library. That it's well implemented is rather inconsequential to it's popularity among many. However, you should certainly be reading more code, we all should.
JSLint can be very helpful in identifying problems with the code, even if JQuery doesn't pass the standards it desires.
JSLint helps you catch problems, it isn't a test of validity or a replacement for thinking. jQuery is pretty advanced as js goes, which makes such a result understandable. I mean the first couple of lines are speed hacks, no wonder the most rigid js parser is going have a couple of errors.
In any case, the assumption that popular code is perfectly correct code or even 'good' is flawed. JQuery code is good, and you can learn a lot of from reading it. You should still run your stuff through JSLint, if only because it's good to hear another opinion on what you've written.
From JSLint's description:
JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language.
"jQuery is very popular so it must have a certain degree of good coding."
One would like to hope this is the case with jQuery, but unfortunately it's not really true. jQuery is useful and popular, but it is not a well written JavaScript library. David Mark recently posted a scathing critique of jQuery in comp.lang.javascript that examines a large number of examples of the poor code found in jQuery:
http://groups.google.com/group/comp.lang.javascript/msg/37cb11852d7ca75c?hl=en&
If you're not actively developing jQuery itself, why even run JSLint over it at all? If it works, it works, and you don't have to worry about it.
The jQuery developers' goals are not the same as your goals. jQuery is built for speed and compactness and achieving those goals trumps readability and maintainability.
Crockford's tests in JSLint have more to do with achieving something that he would feel comfortable taking home to meet his mother, which is a valid concern if you will be married to your code for some time.
The purpose of JsLint is clearly stated in the FAQ [1]:
"JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language."
Now if you are confused: ECMA3 is already a subset of the JS capabilities provided by any of todays JS interpreters (see [2] for an overview of the relation between JavasScript and ECMAScript versions)
To answer the quesition "what good is JSlint":
* use JsLint to verify you are using a "safe" subset of Javascript that is unlikly to break accross JS implementations.
* use Jslint to verify you followed the crockford code conventions [4]
[1] http://www.jslint.com/lint.html
[2] https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/JavaScript_Overview#Relationship_between_JavaScript_Versions_and_ECMAScript_Editions
[3] https://developer.mozilla.org/en/New_in_JavaScript_1.7#Avoiding_temporary_variables
[4] http://javascript.crockford.com/code.html
I've found one case where JSLint is very, very useful: when you grab one of those big-arse libraries that float around the 'Net, then another, then again one other, you soon find yourself loading 50k of Javascript on every new page load (caching may help, but it's not a cure-all solution).
What would you do then? Compress those libraries. But your host doesn't do compression for non-html file! So what? You use a Javascript compressor.
The best I've found is Dean Edward's; I used it to compress John Fraser's Showdown (a Markdown for Javascript library), but unfortunately, the compression broke the code. Since Showdown isn't supported anymore, I had to correct it myself - and JSlint was invaluable for that.
In short, JSlint is useful to prepare your JS code for heavy duty compression.
If you like to daisy-chain methods like jQuery allows you, you might appreciate YUI3.
JQuery is of course not the best thing in the world. That's already clear when you look at the notation. The dollar parentheses combination is really bad for your eyes. Programming should be clear and simple. JQuery is far from that. That reason is enough for me not to use it. That it's not properly written doesn't surprise me and only underscores my thoughts on this JavaScript library.