Nat*_*all 5 javascript performance inline
我的问题涉及通过函数内联的现代浏览器优化.我想我真的需要熟悉V8,JavaScriptCore和/或SpiderMonkey代码库的人来回答这个问题.或至少知道现代浏览器优化方法的人.
基本上我想知道是否有任何方法可以预测何时使用函数内联以及如何利用它来优化性能,同时最小化代码重复.
我们以joi tempo 的以下简单函数为例:
function limit(f, max) {
var count = 0, isFunction = typeof max == 'function';
if(!isFunction) max = max >>> 0 || 1;
return function limitedFunction() {
if(isFunction ? !max(count) : (count >= max)) return;
count++;
return f.apply(this, arguments);
};
}
Run Code Online (Sandbox Code Playgroud)
此函数接受一个函数f并返回一个包装函数,该函数限制了通过包装器调用原始函数的次数.例:
var foo = limit(function() { console.log('foo'); }, 3);
foo(); // logs 'foo'
foo(); // logs 'foo'
foo(); // logs 'foo'
foo(); // doesn't log anything
foo(); // doesn't log anything
Run Code Online (Sandbox Code Playgroud)
它还接受一个返回true或false作为其第二个参数(而不是数字)的函数:
var bar = limit(
function() { console.log('bar'); },
function() { return Math.random() > 0.5 ? true : false }
);
bar(); // randomly logs 'bar' or doesn't log anything
bar(); // randomly logs 'bar' or doesn't log anything
bar(); // randomly logs 'bar' or doesn't log anything
Run Code Online (Sandbox Code Playgroud)
这是一个过于简单,琐碎的例子,所以请耐心等待.我认为在非平凡的情况下有真正的应用程序,但我想使用一个简单的案例来了解浏览器如何或可以进行内联的根源.
重写此函数的一种方法是(可能)(非常轻微地)改进性能(我想象)将返回function分成两种情况,一种max是函数,另max一种是数字:
function limit(f, max) {
var count = 0, isFunction = typeof max == 'function';
if(!isFunction) max = max >>> 0 || 1;
return isFunction
? function limitedFunctionA() {
if(!max(count)) return;
count++;
return f.apply(this, arguments);
}
: function limitedFunctionB() {
if(count >= max) return;
count++;
return f.apply(this, arguments);
};
}
Run Code Online (Sandbox Code Playgroud)
这样的检查,看是否isFunction是true还是false没有发生,每次 limitedFunction被调用但只有一次,当确定是否返回limitedFunctionA或limitedFunctionB.但是,这并不理想,因为存在一些冗余代码.
我的问题涉及以下重写:
function limit(f, max) {
var count = 0, isFunction = typeof max == 'function',
check = isFunction
? function() { return !max(count); }
: function() { return count >= max; };
if(!isFunction) max = max >>> 0 || 1;
return function limitedFunction() {
if(check()) return;
count++;
return f.apply(this, arguments);
};
}
Run Code Online (Sandbox Code Playgroud)
所以这是我的问题...... 现代浏览器是否足够智能化
if(check()) return;
Run Code Online (Sandbox Code Playgroud)
成
if(!max(count)) return;
Run Code Online (Sandbox Code Playgroud)
什么时候isFunction是真的,而且
if(count >= max) return;
Run Code Online (Sandbox Code Playgroud)
何时isFunction是假的?...防止需要调用额外的check()函数,每次都不必要地将额外的函数抛到堆栈上.
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |