Java:比较int和字符串 - 性能 [英] Java: Comparing ints and Strings - Performance

查看:710
本文介绍了Java:比较int和字符串 - 性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String和一个int,让我们说: String str =12345; int num = 12345; 。如果它们是相同的,最快的方式是什么, str.equals(+ num) num == Integer.parseInt )(或者有更快的方法吗?)

I have a String and an int, lets say: String str = "12345"; and int num = 12345;. What is the fastest way of seeing if they are the same, str.equals("" + num) or num == Integer.parseInt(str) (Or is there a faster way?)?

这是 Integer.parseInt < a>和 String.equals

推荐答案

num == Integer。 parseInt(str)的速度会快于 str.equals(+ num)

str.equals(+ num)将首先将num转换为字符串,即O(n),其中n是数字中的位数。然后它会做一个字符串连接再次O(n),然后最后做字符串比较。在这种情况下,字符串比较将是另一个O(n) - n是数字中的位数。所以在所有〜3 * O(n)

str.equals("" + num) will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)

num == Integer.parseInt(str)字符串转换为整数,再次是O(n),其中n是数字中的位数。然后整数比较为O(1)。所以只有〜1 * O(n)

num == Integer.parseInt(str) will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)

总结两个都是O(n) - 但 str.equals(+ num) / code>有一个较高的常数,所以速度较慢。

To summarize both are O(n) - but str.equals("" + num) has a higher constant and so is slower.

这篇关于Java:比较int和字符串 - 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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