有什么可以保证在 JavaScript 中访问对象属性的时间恒定吗? [英] Is there anything that guarantees constant time for accessing a property of an object in JavaScript?

查看:8
本文介绍了有什么可以保证在 JavaScript 中访问对象属性的时间恒定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于我在亚马逊面试时与面试官的一场辩论.

This is in regards to a debate I had with an interviewer when I was interviewing at Amazon.

让我们创建一个对象:

var Obj = {};
Obj['SomeProperty'] = function ( ) { console.log("Accessed some property"); };
Obj[69] = true;

JavaScript 中是否有任何内容保证,当我随后访问这 2 个属性时,例如 Obj['SomeProperty']Obj[69] 各自的值 function ( ) { console.log("Accessed some property");};69 在 O(1) 时间内查找?我知道访问运算符 [] 给经验丰富的程序员的印象是他正在处理 O(1) 查找结构,但是 JavaScript 引擎不可能实现 Object 以某种方式在 O(1) 中查找属性?

Is there anything in the JavaScript guaranteeing that when I subsequently access those 2 properties like Obj['SomeProperty'] and Obj[69] the respective values function ( ) { console.log("Accessed some property"); }; and 69 are looked up in O(1) time? I know the access operator [] gives a seasoned programmer the impression that he's dealing with an O(1) lookup structure, but can't it be possible for a JavaScript engine to implement Object in a way such that properties are not looked up in O(1)?

推荐答案

JavaScript 中是否有任何东西可以保证在 O(1) 时间内查找值?

Is there anything in the JavaScript guaranteeing that the values are looked up in O(1) time?

没有.JavaScript 不提供任何复杂性保证,ES6 集合除外.

No. JavaScript does not give any complexity guarantees whatsoever, except for ES6 collections.

我知道访问运算符 [] 会给一个经验丰富的程序员的印象是他正在处理一个 O(1) 查找结构

I know the access operator [] gives a seasoned programmer the impression that he's dealing with an O(1) lookup structure

是的,这是一个合理的期望.引擎采用各种优化,从哈希映射上的隐藏类到动态数组,以满足这些假设.

Yes you are, this is a reasonable expectation. Engines employ all kinds of optimisations, from hidden classes over hashmaps to dynamic arrays, to meet these assumptions.

当然,永远不要忘记 JS 对象是复杂的野兽,访问一个简单的属性可能会触发一个 getter 陷阱,而这个陷阱又可以做任何事情.

Of course, never forget that JS objects are complex beasts, and accessing a simple property might trigger a getter trap that in turn could do anything.

JavaScript 引擎不能以某种方式实现 Object,从而不会在 O(1) 中查找属性吗?

Can't it be possible for a JavaScript engine to implement Object in a way such that properties are not looked up in O(1)?

是的,这是可能的.

这篇关于有什么可以保证在 JavaScript 中访问对象属性的时间恒定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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