简体   繁体   English

通过 getElementById() 与 var speed 选择元素

[英]Selecting element via getElementById() vs var speed

Could someone pls explain why selecting element through variable is faster than just using DOM query getElementById()?有人可以解释为什么通过变量选择元素比仅使用 DOM 查询 getElementById() 更快吗? As I understand in the first case we ask interpreter to look through DOM tree for an element whose id is 'box' and once found interpreter returns its address.据我了解,在第一种情况下,我们要求解释器在 DOM 树中查找 id 为“box”的元素,一旦找到,解释器就会返回其地址。 In the second case we store the address in variable first and then if we want to select the element we still need to lookup a var with the address that we need.在第二种情况下,我们首先将地址存储在变量中,然后如果我们想要 select 元素,我们仍然需要使用我们需要的地址查找 var。 So how looking up a var is faster than looking up the element itself?那么如何查找 var 比查找元素本身更快呢?

//1
getElementById('box');

//2
var itemOne = getElementById('box');
itemOne;

When you run the getElementById it parses the DOM every time you run it.当您运行getElementById时,它会在您每次运行时解析 DOM。 Once you allocate memory and store the result, the parsing is no longer needed, and the result is retrieved directly from the memory.一旦分配 memory 并存储结果,就不再需要解析,直接从 memory 中检索结果。 I assume that's why it's faster.我认为这就是它更快的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM