问题
I was looking at an answer to an SO question today where the variable names are ua, rv, etc. And I thought, "Man, when will people learn to use full-size variable names, memory is not a problem any more" but then, it is Javascript so it has to come across the wire and perhaps long variable names even slow down interpretation.
Is using short variable names in Javascript premature optimization?
While I'm here, are there any libraries for Rails or PHP that will compress Javscript on the fly, so I can keep my Javascript with long names on the server?
回答1:
The only reason to use short variable names in JS is to save bytes over the wire. However, developing like that is ridiculous. Do they write JS without whitespace, too? There are tools which optimize finished JS. Crockford's is one of the most popular (though it does not shorten variable names). I can't recall offhand one that does obfuscate/shorten variable names, but they do exist and it's not that hard to write one, either. Google Closure is a very impressive JavaScript compiler that turns this:
var myFunction = function(arg1, arg2) {
var foo = getValue(arg2);
for(var count = 0; count < arg1.length; count++) {
alert(foo);
}
};
into this:
function a(b,c){var d=e(c);for(var f=0;f<b.length;f++){alert(d)}}
回答2:
Dont use short variable names for optimization, during development. That would severely decrease readability. Compress your JS/CSS files at compile/deploy time, using something like YUI Compressor.
回答3:
People use short variable names in javascript purely to save on bandwidth. It does not affect execution speed of the javascript. And I don't know about rails or PHP libraries, but there are certainly tools out there that can compress your javascript files (by renaming variables to be shorter and removing unnecessary whitespace).
回答4:
We have not any reason to use not readable code at development.
As the other answers, I think you have a lot of resources to save bandwith and make happy the user with a fast load of the page.
Check these articles:
close-look-into-include-javascript-compression
Production-Grade-JS
回答5:
I normal development, most of these answers are correct. There is no reason to use non-descriptive variable names.
However, when writing answers and examples on SO, variables don't necessarily mean anything in particular. They're just there for demonstration purposes, and have no need for any semantic meaning.
来源:https://stackoverflow.com/questions/918635/two-letter-variable-names-in-javascript