Skip to content

impl Ord for bool: optimization #66780

Closed
@carado

Description

@carado

Currently, impl Ord for bool converts the bools to u8s and then compares them.

On the playground,

pub fn using_ord(x: bool, y: bool) -> Ordering {
    x.cmp(&y)
}

compiles to

playground::using_ord: # @playground::using_ord
# %bb.0:
	movl	%edi, %ecx
	xorl	%esi, %ecx
	testl	%esi, %esi
	movl	$255, %eax
	cmovel	%ecx, %eax
	testl	%edi, %edi
	cmovnel	%ecx, %eax
                                        # kill: def $al killed $al killed $eax
	retq
                                        # -- End function

A much shorter (in instruction count) and almost certainly faster version taking advantage of the fact that orderings are represented by i8 values -1, 0, and 1, is:

pub fn minus_transmute(x: bool, y: bool) -> Ordering {
    unsafe { std::mem::transmute(x as i8 - y as i8) }
}

which on the playground compiles to

playground::minus_transmute: # @playground::minus_transmute
# %bb.0:
	movl	%edi, %eax
	subb	%sil, %al
                                        # kill: def $al killed $al killed $eax
	retq
                                        # -- End function

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions