-1

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?

user3840170
  • 26,597
  • 4
  • 30
  • 62
  • 7
    Better question should be "is there a better way to do it to avoid adding 104 event listeners?" Event Delegation is the answer. – epascarello Apr 10 '23 at 19:00
  • @epascarello listeners are in different places – y e n i m a l Apr 10 '23 at 19:01
  • @epascarello and project is big – y e n i m a l Apr 10 '23 at 19:03
  • 2
    I'll take a guess that you have 104 elements that you apply the `.addEventListener` to. If so, probably consider event delegation, so you only define the element once. Otherwise, you save *about* half a megabyte by doing this. You can probably save significantly more if you either minify your code or you use gzip when sending the code. And the latter is probably already done anyway. – VLAZ Apr 10 '23 at 19:03

1 Answers1

2

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375