Skip to content

comparison_chain suggestion can be a performance regression #5354

Description

@sourcefrog

clippy 0.0.212 (23549a8 2020-03-16)
rustc 1.44.0-nightly (f509b26 2020-03-18) on macos

clippy suggests rewriting some chained if/else blocks in my code, like so

-    let y = l[0];
-    if y > x {
-        return 0;
-    } else if y == x {
-        b = 0;
-    } else {
-        a = 1;
-        c = 1;
-    }
+    match l[0].cmp(&x) {
+        Ordering::Greater => return 0,
+        Ordering::Equal => b = 0,
+        Ordering::Less => {
+            a = 1;
+            c = 1;
+        }
+    };

This is semantically the same and arguably cleaner. But, according to a Criterion microbenchmark, Clippy's suggestion is significantly slower than the chained comparisons.

It looks like this might be related to the simple comparison being inline, versus the cmp remaining as

    call    core::cmp::impls::<impl core::cmp::Ord for i32>::cmp

Probably in many cases the performance difference isn't noticeable and it's better style, but perhaps there should at least be a caveat in the Clippy docs.

(Also, ideally the compiler should be smart enough to make it just as fast.)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-documentationArea: Adding or improving documentationgood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions