Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a frozen "enum" slower?

In order to access the data in an array I created an enum-like variable to have human readable identifiers to the fields.

var columns = { first: 0, second: 1 };
var array = ['first', 'second'];
var data = array[columns.first];

When I found out about Object.freeze I wanted to use this for the enum so that it can not be changed, and I expected the VM to use this info to its advantage.

As it turns out, the tests get slower on Chrome and Node, but slightly faster on Firefox (compared to direct access by number).

The code is available here: http://jsperf.com/array-access-via-enum

Here are the benchmarks from Node (corresponding to the JSPerf tests):

  fixed Number: 12ms
  enum: 12ms
  frozenEnum: 85ms

Does V8 just not yet have a great implementation, or is there something suboptimal with this approach for my use-case?

like image 528
Timm Avatar asked Apr 17 '13 10:04

Timm


1 Answers

I tried your test in Firefox 20, which is massively faster across the board, and IE 10 which slightly faster and more consistant.

So my answer is No, V8 does not yet have a great implementation

like image 153
Colin Pickard Avatar answered Oct 15 '22 19:10

Colin Pickard