thisissami
thisissami

Reputation: 16383

In JavaScript/nodejs, is there a speed difference between accessing a variable vs a property of a variable?

I'm essentially writing a little script that needs to save several different files as variables and then return them on request. I'm trying to write the fastest version possible (the tiniest minute difference is actually important to me here).

In terms of coding, it'll be a lot simpler/shorter if I save the files all as the property of a variable, since then I can do things like:

var files = {}
readfile(path, name){
  fs.readFile(path, function(err, buf){    //nodejs function
    files[name] = buf;
  });
}

and have that same function used for each of the files I'm saving into memory.

However, when later accessing the files, will it take more time to return something that's a property of a variable as opposed to its own variable? The slightest time saved actually makes a difference for my application, so I'm willing to rewrite the same block of code again and again with different variables if that'll make things ever so slightly quicker.

Alternatively is there another way to do the same thing as the code example just passing in a variable name to replace files[name] that I'm not aware of?

Upvotes: 0

Views: 301

Answers (1)

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35283

Accessing a property is probably slower, but current engines are so optimized that you couldn't even measure it. When you're doing I/O this doesn't make any difference, you're never going to read 200 million files per second in a single process. For all matters, consider variable/method/property access as free.

Anyway, here's a performance shootout just in case: http://jsperf.com/var-vs-property

Upvotes: 2

Related Questions