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

ตัวดำเนินการ < และ <= ใน C/C++ อันไหนเร็วกว่า?

ไม่มีความแตกต่างด้านความเร็ว ทั้ง < และ <= ใช้เวลารันเท่ากัน

เหตุผล

ระดับ Assembly ใช้ Jump Instructions (JCC) ตามประเภทการเปรียบเทียบ:

  • je − Jump if Equal
  • jg − Jump if Greater
  • jne − Jump if Not Equal
  • jge − Jump if Greater or Equal

< ใช้ jg ส่วน <= ใช้ jge ทั้งคู่ใช้ Cycle เดียวกันบน CPU สมัยใหม่

ตัวอย่างโค้ด

#include <stdio.h>

int main() {
    int a = 8, b = 8;
    if (a < b)
        printf("b is greater than a\n");
    if (a <= b)
        printf("b is greater or equal to a");
    else
        printf("b is smaller than a");
    return 0;
}

ผลลัพธ์

b is greater or equal to a

สรุป

เลือกใช้ตาม Logic ที่ต้องการ ไม่ต้องกังวล Performance คอมไพเลอร์สมัยใหม่ Optimize ให้เท่ากันแล้ว