Why does Object.keys return an Array instead of a Set?

Herby Vojčík herby at mailbox.sk
Tue Oct 27 08:24:24 UTC 2020


On 27. 10. 2020 0:11, #!/JoePea wrote:
> Interesting, on my system I consistently see Set iteration is faster
> (I replayed it many times). I'm in Chrome 85, Linux. This might be
> temporary.
> 
>> `new Set(Object.keys(obj))`
> 
> That creates two objects and an iteration (will the engine optimize
> that away?), while `Object.keySet` (or similar) would surely create a
> single object.
> 
> #!/JoePea

Just a speculation here, but it depends on the shape of obj. If obj has 
internal map, then Object.keys(obj) is internal constant structure, 
known to contain unique items. If arrays have a flag for "known to be 
unique", maybe combined with "known to not be mutated", both new 
Set(...) created from such structure and iterations can be pretty 
well-optimized.

Herby

> On Sun, Oct 18, 2020 at 10:19 AM Jordan Harband <ljharb at gmail.com> wrote:
>>
>> `new Set(Object.keys(obj))` seems pretty straightforward - I doubt it's worth adding something to the language just to make that shorter.
>>
>> Separately, if you're looking for a deduped O(1) lookup of key presence, you already have _an object_ - `Object.prototype.hasOwnProperty.call(obj, key)`.
>>
>> On Sun, Oct 18, 2020 at 8:28 AM Ehab Alsharif <ehalsharif92 at gmail.com> wrote:
>>>
>>> Other than the fact that Object.keys existed really before Sets, you are comparing apples and oranges here in your benchmarks.
>>> the include method has to scan the array in order to find elements, but sets are objects which are just hash tables.
>>> Also you typically don't get the keys array to check that a key is there, you can do that directly using the object you have.
>>> Another thing is that the typical use case for Object.keys is to get an iterator over the keys, returning a set for that purpose does not serve that purpose directly.
>>>
>>> On Sat, Oct 17, 2020 at 4:51 AM #!/JoePea <joe at trusktr.io> wrote:
>>>>
>>>> Sets are faster, even for tiny lists of four items. See the perf tests
>>>> (tested in Chrome):
>>>>
>>>> https://twitter.com/trusktr/status/1315848017535098880
>>>>
>>>> https://twitter.com/trusktr/status/1317281652540731392
>>>>
>>>> #!/JoePea
>>>> _______________________________________________
>>>> es-discuss mailing list
>>>> es-discuss at mozilla.org
>>>> https://mail.mozilla.org/listinfo/es-discuss
>>>
>>> _______________________________________________
>>> es-discuss mailing list
>>> es-discuss at mozilla.org
>>> https://mail.mozilla.org/listinfo/es-discuss
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
> 



More information about the es-discuss mailing list