Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ทำให้โค้ดเร็วขึ้นด้วย JavaScript Sets

เพื่อเข้าใจวิธีทำให้โค้ดเร็วขึ้นด้วย Sets ต้องเข้าใจสถานการณ์ที่ควรใช้ Sets แทน Arrays

  • เนื่องจาก Sets เก็บ unique elements เท่านั้น เหมาะหากรู้ล่วงหน้าอยากหลีกเลี่ยง duplicate data

  • Basic operations ของ Set เช่น union(), intersect(), difference() implement ได้ง่ายและมีประสิทธิภาพจาก built-in operations ด้วย delete() method ทำให้ intersect/union ระหว่าง 2 Sets สะดวกและเร็วกว่า Arrays มาก Random deletes ใน Sets เป็น O(1) ในขณะที่ Arrays เป็น O(n)

  • Arrays เหมาะสำหรับ ordered และ index-based access หรือการกระทำที่ต้องการ direct index access (เช่น Binary Search) Sets เหมาะสำหรับตรวจสอบและ validate membership ของ objects ใน collections

Search heavy scenarios ควรใช้ Sets เช่น authorization/authentication ตรวจสอบ membership ของคนในกลุ่มต่างๆ

ที่ต้องการ order และ duplicate data ควรใช้ Arrays เช่น sorted collection of objects

หมายเหตุ - Sets ต่างจาก Arrays ไม่ได้แทนที่ Arrays แต่ให้ additional support