应该将传递给 addEventListener 的事件名称放入专用的常量中以节省空间吗?

huangapple go评论61阅读模式
英文:

Should I put event names passed to addEventListener in dedicated constants to save space?

问题

在我的项目中,我有104个addEventListener调用,用于将处理程序附加到mousedown事件。

所以我决定为这些事件名称使用变量,例如:

var md = "mousedown";
element.addEventListener(md, function(){});

以减少下载的字节数。

这是否是一个好的做法?我是否获得了更高性能的代码?

英文:

In my project I have 104 addEventListener calls attaching handlers to the mousedown event.

So I decided to use variables for those event names, like: 

var md = "mousedown";

element.addEventListener(md, function(){}); 

to reduce downloaded bytes.

Is it good practice? Did I get more performant code?

答案1

得分: 2

不是好的实践。不要修改源代码以减少下载字节数 - 要修改源代码以避免重复,以正确分离关注点,以减少耦合并提高可读性。引入一个名为md的额外全局变量并不能达到这个目的。相反,考虑使用辅助函数来包装整个addEventListener调用 - 毫无疑问,你的104个事件监听器除了事件名称之外应该还有更多共享的代码。

减少要下载的字节数是缩小器、传输压缩和缓存的工作。前两者将很好地处理字符串"mousedown"的重复出现。

我希望这些翻译对您有所帮助。

英文:

> Is it good practice?

No. Do not modify your source code to reduce download bytes - modify it to avoid duplication, to properly separate concerns, to reduce coupling and to make it more readable instead. Introducing an extra global variable ambiguously named md does not do that. Rather consider a helper function to wrap the whole addEventListener call - surely your 104 event listeners share more code than just the event name?

Reducing the number of bytes to be downloaded is the job of a minifier, transport compression, and caching. The former two will handle repeated occurrences of the string "mousedown" just fine.

> Did I get more performant code?

Unlikely. String literals are usually interned by the engine anyway, and a variable lookup (even for a constant) takes extra time.

huangapple
  • 本文由 发表于 2023年4月11日 03:00:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75979889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定