java String和int区别,Java:比较int和字符串 - 性能

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?)?

This is the source code for Integer.parseInt and String.equals

解决方案

num == Integer.parseInt(str) is going to faster than str.equals("" + num)

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) 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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值