swift 代碼java
func getDigits(with number: Int) -> Int { var digit = 1 var num = number while num / 10 != 0 { num /= 10 digit += 1 } return digit } var stringTime: TimeInterval = 0 var digitTime: TimeInterval = 0 for _ in 0 ..< 10000000 { let num = Int(arc4random()) do { let start = Date().timeIntervalSince1970 let _ = String(num).count let end = Date().timeIntervalSince1970 stringTime += (end - start) } do { let start = Date().timeIntervalSince1970 let _ = getDigits(with: num) let end = Date().timeIntervalSince1970 digitTime += (end - start) } } print("轉換成字符串: \(stringTime)") print("經過計算: \(digitTime)") 複製代碼
Java 代碼git
import java.util.Date; import java.util.Random; class Digit { public static void main(final String[] args) { Random r = new Random(); long stringTime = 0; long digitTime = 0; for (int i = 0; i < 10000000; i++) { int number = r.nextInt(10); { long start = (new Date()).getTime(); int count = ("" + number).length(); long end = (new Date()).getTime(); stringTime += (end - start); } { long start = (new Date()).getTime(); int count = Digit.getDigits(number); long end = (new Date()).getTime(); digitTime += (end - start); } } System.out.print("轉換成字符串:"+ stringTime+"\n"); System.out.print("經過計算:"+ digitTime+"\n"); } static int getDigits(final int number) { int digit = 1; int num = number; while (num / 10 != 0) { num /= 10; digit += 1; } return digit; } } 複製代碼
Swift 10次樣本 單位:sswift
序號 | 轉換成字符串 | 經過計算 |
---|---|---|
1 | 1.6021199226379395 | 2.122344493865967 |
2 | 1.6038966178894043 | 2.126537322998047 |
3 | 1.6078293323516846 | 2.1316823959350586 |
4 | 1.5953664779663086 | 2.11974835395813 |
5 | 1.6008284091949463 | 2.1262362003326416 |
6 | 1.5975737571716309 | 2.117039918899536 |
7 | 1.573176383972168 | 2.0912203788757324 |
8 | 1.553645372390747 | 2.068214178085327 |
9 | 1.5619103908538818 | 2.075680732727051 |
10 | 1.5425021648406982 | 2.0574917793273926 |
Java 10次樣本 單位:msmarkdown
序號 | 轉換成字符串 | 經過計算 |
---|---|---|
1 | 686 | 453 |
2 | 533 | 427 |
3 | 508 | 447 |
4 | 516 | 395 |
5 | 528 | 419 |
6 | 515 | 416 |
7 | 511 | 376 |
8 | 523 | 362 |
9 | 526 | 397 |
10 | 524 | 384 |
疑問:一樣是很大的數字 Swift 的表現是轉成字符串獲取位數比直接計算的方式耗時少, 而在 java 中表現相反 而且 java 總體用時好像比 swift 要少 why???dom