Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Symbols vs number literal?

Tags:

javascript

I've been using object literals as a poor man's enum, something like this:

let enum = {
    option1: Symbol("o1"),
    option2: Symbol("o2"),
    option3: Symbol("o3")
};

let item = enum.option2;

if(item === enum.option2) { console.log("Item is Option 2!") }

I use Symbol because I think it makes more semantic sense than using numbers -- in this case I don't really care about which value the "enum" carries, I just want to check equality -- but am slightly worried about performance considerations of doing it that way. Am I putting a bigger strain on the processor if I keep using Symbols in place of integers?

like image 990
Rafael Avatar asked Sep 06 '25 04:09

Rafael


1 Answers

No, symbols are primitive values just like numbers and should be compared equally fast. The only downside might be that you have to use a variable to refer to them instead of a trusted literal, but if your variables are const and never assigned, an optimising compiler should be able to inline symbol values as well.

In any case, you should definitely use what makes more sense semantically, and helps you with development performance. Execution speed is secondary, and the difference here will be negligible.

like image 166
Bergi Avatar answered Sep 08 '25 17:09

Bergi