Re:"Calling oneself a C Programmer is like saying you're a H...
by Unosolo on Tuesday October 26, 2010 @08:50AM
(#1833956)
It's a good example of how coming from different language can both help and inhibit programmer's thinking. Knowing C certainly helps to understand that repetitive array size and index access is likely to be more expensive than using local variables. At the same time C programmer is more likely to adopt an imperative programming style, which is in this case more error prone, verbose and doesn't allow for code re-use.
More ideomatic JavaScript would look like this:
Array.prototype.foreach = function (f) {
for (var i = 0, _i = this.length; i < _i; i++) f(this[i])
}
/** BEGIN **/
var f = new Array(3000000);
console.time(1);
f.foreach( function (el) {
if (el === 'foobar' ||
el === 'foobaz' ||
el === 'baz' ||
el === 'barfoo') // Do something
})
console.timeEnd(1);
/** END **/
Take the following code for example:
On my comp, in Firefox, this executes in 7478 ms.Now, if there is one thing that pointer arithmetic has taught me to be especially aware of is that array index lookups are expensive, usually regardless of the language. With this knowledge, I am empowered to refactor my code to look like this:
On my comp, in Firefox, this runs in 6235 ms. Now, I have achieved almost a 20% performance increase due to my expanded world view.This is a very simple example, but the list goes on. One certainly should not limit themself to one language.