compareTo with primitives - >整数/ int [英] compareTo with primitives -> Integer / int

查看:145
本文介绍了compareTo with primitives - >整数/ int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

写字是否更好

int primitive1 = 3, primitive2 = 4;
Integer a = new Integer(primitive1);
Integer b = new Integer(primitive2);
int compare = a.compareTo(b);

int primitive1 = 3, primitive2 = 4;
int compare = (primitive1 > primitive2) ? 1 : 0;
if(compare == 0){
    compare = (primitive1 == primitive2) ? 0 : -1;
}

我认为第二个更好,应该更快,更多内存优化。但它们不相等吗?

I think the second one is better, should be faster and more memory optimized. But aren't they equal?

推荐答案

为了提高性能,通常最好使代码尽可能简单明了通常会表现良好(因为JIT会优化此代码)。在你的情况下,最简单的例子也可能是最快的。

For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.

我会这样做

int cmp = a > b ? +1 : a < b ? -1 : 0;

或更长的版本

int cmp;
if (a > b)
   cmp = +1;
else if (a < b)
   cmp = -1;
else
   cmp = 0;

int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7

如果不需要,最好不要创建对象。

Its best not to create an object if you don't need to.

性能明智,第一个是最好的。

Performance wise, the first is best.

如果您确定不会出现溢出你可以使用

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow.

你不会比这更快。

这篇关于compareTo with primitives - &gt;整数/ int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆