为什么在删除之前使用点表示法检查属性比直接删除属性更快? [英] Why is checking for an attribute using dot notation before removing faster than removing the attribute outright?

查看:70
本文介绍了为什么在删除之前使用点表示法检查属性比直接删除属性更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了这个问题,结果证明从元素中删除属性时,使用 elem.xxx!== undefined 检查元素是否首先存在会使运行时更快。 证明

I asked this question, and it turned out that when removing an attribute from an element, checking whether the element exists first using elem.xxx!==undefined makes the runtime faster. Proof.

为什么它更快? 需要更多代码,你必须遇到 removeAttribute()无论你采用哪种方式。

Why is it quicker? There's more code to go through and you'll have to encounter the removeAttribute() method whichever way you go about this.

推荐答案

嗯,首先你需要知道的是 elem.xxx elem.getAttribute()或与该属性相关的任何其他方法不同。

Well, first thing you need to know is that elem.xxx is not the same as elem.getAttribute() or any other method relative to the attribute.

elem.xxx 是DOM元素的属性,而DOM内部的HTML上的属性和元素都相似但不同。例如,请使用以下DOM元素:< a href =#> 并且此代码:

elem.xxx is a property of a DOM element while attribute and element on the HTML inside the DOM, both are similar but different. For exemple, take this DOM element: <a href="#"> and this code :

//Let say var a is the <a> tag
a.getAttribute('href');// == #
a.href;// == http://www.something.com/# (i.e the complet URL)

但是,请使用自定义属性:< a custom =test>

But let take a custom attribute : <a custom="test">

//Let say var a is the <a> tag
a.getAttribute('custom');// == test
a.custom;// == undefined

所以你无法真正比​​较两者的速度,因为它们没有达到相同的结果。但是一个显然更快,因为属性是快速访问数据,而属性使用get / hasAttribute DOM函数。

So you can't really compare the speed of both since they don't achieve the same result. But one is clearly faster since properties are a fast access data while attribute use the get/hasAttribute DOM functions.

现在,为什么没有条件更快?仅仅因为 removeAttribute 并不关心属性是否缺失,它会检查它是否不存在。

Now, Why without the condition is faster? Simply because removeAttribute doesn't care is the attribute is missing, it check if it is not.

所以使用 hasAttribute 之前 removeAttribute 就像执行两次检查一样,但条件有点慢,因为它需要检查是否条件满足运行代码。

So using hasAttribute before removeAttribute is like doing the check twice, but the condition is a little slower since it need to check if the condition is satisfied to run the code.

这篇关于为什么在删除之前使用点表示法检查属性比直接删除属性更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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