Swift本地与全局范围数组

时间:2014-08-05 20:06:41

标签: arrays performance swift

在这个论坛中,Swift beta并不是阵列性能领域的赢家。

但有没有人注意到Swift在处理全局声明的数组时完全丢失了?

看一下下面的代码片段。我测量的回复时间是彻头彻尾的惨败。我无法想到导致这种荒谬结果的场景,并使我的Macbook 2014处理器全速运行。

我错过了什么或是否有一些解释?拜托我。

let maxElements = 1000000;
.   
.      
.
func printElapsedTime(startTime: NSDate, message: String) {
  let endTime = NSDate();
  println(message + ": " + NSString(format:"%.6f", endTime.timeIntervalSinceDate(startTime)) + " sec");
}

func benchMark1() {
  var localArray = Array(count:maxElements, repeatedValue:String());

  let someString = "Percy Jackson - The Titan's Curse";
  var anotherString: String;

  var startTime = NSDate();
  for i in 0..<maxElements {
    localArray[i] = someString;
  }
  printElapsedTime(startTime, message: "Elapsed time for creating and altering a local array");

  startTime = NSDate();
  for i in 10..<20 {
    anotherString = localArray[i];
  }
  printElapsedTime(startTime, message: "Elapsed time accessing 10 elements of the local array");
}
// Elapsed time for creating and altering a local array: 2.637573 sec
// Elapsed time for read accessing 10 elements of the local array: 0.000039 sec

func benchMark2() {

  var localArray = Array(count:maxElements, repeatedValue:String());
  let someString = "Percy Jackson - The Titan's Curse";
  var anotherString: String;

  var startTime = NSDate();
  for i in 0..<maxElements {
    localArray[i] = someString;
  }
  self.globalArray = localArray;
  printElapsedTime(startTime, message: "Elapsed time for creating/altering a local array and copy it into a global array");

  startTime = NSDate();
  for i in 10..<20 {
    anotherString = globalArray[i];
  }
  printElapsedTime(startTime, message: "Elapsed time accessing 10 elements of the global array");
}
// Elapsed time for creating/altering a local array and copy it into a global array: 9.570817 sec
// Elapsed time read accessing 10 elements of the global array: 143.937524 sec !!!!

0 个答案:

没有答案