英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论