c# - 将 2 个整数与另外 2 个整数进行有效比较
问题描述
我有一段用于比较的代码,它位于被调用数百万次的热路径中。在基准测试之后,那段代码是优化的候选者。
基本上,我有 2 个整数c
和m
. 比较两个对象首先需要检查双方是否相等,然后比较取决于它们的c
值。c
m
c
只能在范围内[0-100]
m
只能在范围内[0-200]
伪代码
if this.c < other.c return -1; // Or any negative number
if this.c > other.c return 1; // Or any positive number
// Both objects have equal 'c' value
if this.m < other.m return -1; // Or any negative number
if this.m > other.m return 1; // Or any positive number
// Both 'c' and 'm' are equal
return 0;
以下 C# 代码是我目前拥有的
int CompareTo(Obj other)
=> _c < other._c || (_c == other._c && _m < other._m)
? -1
: _c == other._c && _m == other._m
? 0
: 1;
我想知道这是否可以进一步优化,也许是位操作?
谢谢
解决方案
比 dxiv 的版本略短,但基于相同的想法:
(this.m - other.m) + ((this.c - other.c) << 8)
所以我们首先比较m
s,然后通过 s 的比较覆盖它,利用c
s 的有限范围m
。
推荐阅读
- c# - 在 TFS 2018 API 中管理工作项的创建和更新
- sql-server - 如何使用 SSIS 中派生列中的表达式解析字符串
- ios - 处理“手机”URL 方案在真实设备上不起作用
- java - 有没有办法将 java bean 添加到 javafx 场景
- javascript - Hubspot drop.js - 未捕获的 ReferenceError:未定义 Drop
- java - 我想创建一个混合器来混合我通过解析 MPEG-DASH URL 获得的音频和视频
- java - Cannot download file from mount point in Tomcat application
- angular - 有什么特别的?类型“节点”不能转换为类型“子节点”
- networking - 在 TextFSM 上从末尾匹配字符串
- android - 如何更改 viewpager 的大小以匹配屏幕而不与其他元素重叠?