Javascript big-O属性访问性能 [英] Javascript big-O property access performance

查看:122
本文介绍了Javascript big-O属性访问性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript属性访问的性能特征是什么(在当前实现中)?




  • 假设数组访问是O是否安全( 1)?

  • 如果我使用一个对象作为哈希表(使用字符串键),我可以安全地假设O(1)或O(log n)访问时间吗?


  • 是否有任何常见的浏览器或环境比其他浏览器或环境明显更快/更慢,我应该留意哪些?


  • JavaScript标准有什么要说的吗?




最重要的是:




  • 我在哪里可以找到这种渐近的JavaScript性能问题的好参考?


解决方案

JavaScript中的每个对象都是作为对象哈希实现的,因此没有功能差异。



<例如,看看这个测试:

  var arr = []; 
arr [5] = 5;
arr ['5'] ='不是5';
console.log(arr.length,arr);
//输出:6 [undefined,undefined,undefined,undefined,undefined,not 5]

当用作职位时,数字会被字符串化。



参见 Crockford的网站关于JavaScript的更多信息。特别重要的部分是在数组标题下:



JavaScript中的数组也是哈希表对象。



性能不是真正的问题,除非你有大量的对象要跟踪(比如500,000+),在这种情况下你可能做错了。



你可以做一些优化,但除非你用JavaScript做一些不自然的事情(比如压缩算法......),它们才真正有意义......我参与了LZMA实现在JS ......糟糕的主意)。



注意:



如果你有备用套件(像你一样)只定义10,000个中的10个索引,你应该使用常规对象。数组会将所有10,000个索引初始化为未定义,而 Object.keys(obj)只会报告您设置的10个索引。这是一个实际上有意义的次要优化。


What are the performance characteristics of JavaScript property access (on current implementations)?

  • Is it safe to assume array access is O(1)?
  • If I use an object as a hash table (with string keys) can I safely assume O(1) or O(log n) access time?

  • Are there any common browsers or environments that are significantly faster/slower than the others and that I should keep an eye for?

  • Do the JavaScript standards have anything to say?

And most importantly:

  • Where can I find good references for this kind of asymptotic JavaScript performance issues?

解决方案

Every object in JavaScript is implemented as an object hash, so there is no functional difference.

For example, check out this test:

var arr = [];
arr[5] = 5;
arr['5'] = 'not 5';
console.log(arr.length, arr);
// output: 6 [undefined, undefined, undefined, undefined, undefined, "not 5"]

Numbers are stringified when used as positions.

See Crockford's website about JavaScript for more information. The especially important part is under the heading "Arrays":

Arrays in JavaScript are also hashtable objects.

Performance isn't really an issue unless you have a ton of objects to keep track of (like 500,000+), in which case you're probably doing something wrong.

There are optimizations you can do, but they don't really make sense unless you're doing something unnatural with JavaScript (like compression algorithms... I worked on an LZMA implementation in JS... bad idea).

Note:

If you have a spare set (like you define only 10 indexes out of 10,000), you should probably be using a regular object. Arrays will initialize all 10,000 indexes to 'undefined', whereas Object.keys(obj) will only report the 10 you have set. This is a minor optimization that actually makes sense.

这篇关于Javascript big-O属性访问性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆