斯威夫特VS爪哇 - 灌浆大数组速度 [英] Swift vs Java - speed at filling big array

查看:88
本文介绍了斯威夫特VS爪哇 - 灌浆大数组速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是做了Java和雨燕之间的填充一个大阵列的小速度对比。
我想出了以下结果:

I just did a small speed comparison between Java and Swift on filling a big array. I came up with following results:

import Foundation

let start = CFAbsoluteTimeGetCurrent()
var intArray = Int[]()
for var i = 0; i <= 300000; ++i {
    intArray.append(0)
}
let timeTaken = CFAbsoluteTimeGetCurrent() - start
println(timeTaken)

结果:1​​.66182696819305

Result: 1.66182696819305

long start = System.currentTimeMillis();
int[] intArray;
int i = 0;
intArray = new int[300000];
for (i = 0; i < 300000; i++) {
    intArray[i]=0;
}
System.out.println("Time: "+(System.currentTimeMillis()-start)+"ms");

结果:时间:3ms的

Result: Time: 3ms

这是种震撼了我;


  • 是斯威夫特550X慢那么Java ..或正在使用一些不优化code我?

推荐答案

有你的两种实现方式的根本区别。

You are comparing apples and pears..

There's a fundamental difference between your two implementations.

您的的Java 的实施将分配内存为所有的 300000 的元素一次,然后将每一个元素的值。

Your java implementation will allocate memory for all 300 000 elements at once, and then set the value of each element.

迅捷的实施将不过的可能的调整在每一个迭代,因为要附加一个元素,而不是将其存储在底层存储特定位置。最大的可能是旧的存储的大小调整+副本将不会发生在每个迭代上,但它是一种可能性;它当然会你的循环过程中发生一次以上。

The swift implementation will however potentially resize the underlying storage on every iteration since you are appending an element, not just storing it at a particular location. Most probably a resize + copy of the old storage will not happen on every iteration, but it's a possibility; and it will certainly happen more than once during your loop.

要解决的迅捷的实施,你应该使用<一个href=\"https://developer.apple.com/library/$p$prelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_142\">array-initializer在直接创造分配所需的存储空间的 intArray 的,如下面的例子:

To fix the swift implementation you should use an array-initializer to allocate required storage directly upon creating the intArray, such as in the below example:

var intArray = Int[](count: 300000, repeatedValue: 0)
for var i = 0; i <= 300000; ++i {
    intArray[i] = 0
}

这篇关于斯威夫特VS爪哇 - 灌浆大数组速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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