开发者

JavaScript: inline function vs. regular statements

开发者 https://www.devze.com 2023-04-06 10:22 出处:网络
Once again I found JavaScript code on the Internet that contains an inline function where, in my opinion, regular statements would make just as much sense. Here\'s the first sample:

Once again I found JavaScript code on the Internet that contains an inline function where, in my opinion, regular statements would make just as much sense. Here's the first sample:

function outerHTML(node){
  // if IE, Chrome take the internal method otherwise build one
  return node.outerHTML || (
         function(n) {
           var div = document.createElement('div'), h;
           div.appendChild(n.cloneNode(true));
           h = div.innerHTML;
           div = null;
           return h;
         })(node);
}

If you'd ask me to code the same thing, it would look like this:

function outerHTML(node){
  var div, h;

  // if IE, Chrome take the internal method otherwise build one
  if (node.outerHTML) {
    return node.outerHTML;开发者_运维百科
  }

  div = document.createElement('div')
  div.appendChild(node.cloneNode(true));
  h = div.innerHTML;
  div = null;

  return h;
}

EDIT: As OverZealous stated, there is a difference in logic on this one. I leave it here so nobody gets confused about that answer.

And maybe another original sample (yes, this doesn't "compile" as it's just a code fragment):

addGetters: function (attributes) {
  var that = this;
  function addGetter(attr) {
    that.prototype["get" + attr.capitalize()] = function() { return this[attr]; };
  }

  for(var i = 0; i < attributes.length; i++) {
    var attr = attributes[i];
    addGetter(attr);
  }
},

compared to my attempt

addGetters: function (attributes) {
  for(var i = 0; i < attributes.length; i++) {
    var attr = attributes[i];
    this.prototype["get" + attr.capitalize()] = function() { return this[attr]; };
  }
},

Is there a difference? Doesn't the original version consume more space since a function needs to be created and/or isn't it slower because of this? Is there a possible memory leak?

The utilisation of CPU and memory is very important as I'm coding in an environment where both are limited and any "less" is good. And since there's no sizeof() in JavaScript and its implementation attempts aren't safe to interpret any thinking-ahead-fixes are important.

Please note that as far as the "my version" is concerned I didn't test it. I'm just trying to explain what I'm trying to ask.

EDIT: Even though this question has an answer, I'm still wondering about the memory utilisation. If somebody has some insights, please don't hesitate to add it here.


For the first one, I don't believe there is any reason for the function. It might have (d)evolved into that state through small changes, but the extra function wrapper isn't providing any benefit that I can see.

The second example, however, is actually critical to use the function wrapper. The reason is due to JavaScript's (sometimes frustrating) function-level scope. In your example, there is only one attr variable. It is shared across the different attributes. This means that, in the end, every attribute will return the value of last attribute in the array.

e.g:

var attrs = ['foo', 'bar', 'baz']
obj.addGetters(attrs);

obj.getFoo(); // returns obj.baz
obj.getBar(); // returns obj.baz

By wrapping the getter creation in a function, you eliminate that issue, because attr ends up being scoped to the creating function. This is why Douglas Crockford's JSLint says "Don't create a function inside a loop". It leads to unexpected bugs like that one.


As OverZealous pointed out, one needs to be sure about the logic that's happening. +1 for that.

As far as the performance is concerned I finally had the time to do some testing on my own. However, I'm working in an environment where I can't really check memory utilisation. So I tried to fool around with the performance.

The result is that it may have an impact depending on how often this feature is used. On my target system the simple creation of an inline function that does close to nothing, e.g.

myArray.each(function inlineFunc(el) { return el; });

takes about 1.8 seconds for 10,000 creations of such a function (in the example above myArray had no elements). Just in comparison the PC-version of that browser needs 1,000,000 iterations to get somewhere close to that (obviously this also depends on the hardware).

Since the 10,000 iterations are reached in the code we use (not directly in one loop, but functions are created all over the code), we will have a word with our subcontractor.


The answer lies in the eye of the beholder.
It's a matter of preference.
It's up to you if you put "speed" above modularity.
Ask yourself this: why do you use a for when it can be done with a while? It is proven that in some cases the while structure is a bit faster.

0

精彩评论

暂无评论...
验证码 换一张
取 消