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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With