Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variables instead of static causes JS to be slow?

Tags:

javascript

I have a library which uses lets say "getAttribute" function of Node a lot. So instead of having it as node.getAttribute(), if I have node[getAttributeStr](), I can have the getAttributeStr as a local string value "getAttribute", which would get minified reducing the size of the code.

My question is, If I do it for all the most frequently used function names, will it slow down the execution as compared to accessing the function directly using the static name?

node.getAttribute("abc");

The above code will be replaced by.

var getAttributeStr = "getAttribute";
node[getAttributeStr]("abc")

My function gets executed quite a lot and hence am afraid if it will increase the execution time a lot.

like image 600
Jagan Avatar asked Apr 09 '19 09:04

Jagan


1 Answers

I quickly threw a jsperf-test together, using your example.

https://jsperf.com/dynamic-vs-static-method-call/1

While they're about the same in chrome, the bracket notation seems to be much slower than the static call in firefox. In Edge, the dot notation is about twice as fast on my machine.

enter image description here

To answer your question, yes it will slow down the execution to a certain degree in some browsers.

However, on most modern machines changing one implementation to the other will be barely noticeable. According to the test, you still can call the dynamic getAttribute 300.000 times per second in the slowest browsers. There are bigger problems with most websites, such as loading 500 KB of tracking scripts and dependencies to display a onepager, requesting non-minified/cached sources, displaying dozens of heavyweight ads etc, which should be attended to first.

like image 117
Tom M Avatar answered Nov 08 '22 14:11

Tom M