Gcc 为什么男人或男孩测试在Objective-C(块)中似乎比在C+中快得多+;(兰姆达)?

Gcc 为什么男人或男孩测试在Objective-C(块)中似乎比在C+中快得多+;(兰姆达)?,gcc,optimization,lambda,clang,objective-c-blocks,Gcc,Optimization,Lambda,Clang,Objective C Blocks,我得到了一个“性能分析”类的作业,并决定使用。我已经完成了我的作业,但出现了一些奇怪的事情 带有块的Objective-C代码(无弧!)如下所示: #import <stdlib.h> #import <assert.h> #import <Foundation/Foundation.h> typedef int (^F)(void); int A(int kParam, F x1, F x2, F x3, F x4, F x5) { __block

我得到了一个“性能分析”类的作业,并决定使用。我已经完成了我的作业,但出现了一些奇怪的事情

带有块的Objective-C代码(无弧!)如下所示:

#import <stdlib.h>
#import <assert.h>
#import <Foundation/Foundation.h>

typedef int (^F)(void);

int A(int kParam, F x1, F x2, F x3, F x4, F x5) {
  __block int k = kParam;
  __block F B;

  B = ^ {
    return A(--k, B, x1, x2, x3, x4);
  };
  return k <= 0 ? x4() + x5() : B();
};

F K(int n) {
    return [[^{
                return n;
              } copy] autorelease];
};

int main(int argc, const char **argv) {
  static int TABLE[] = {1, 0, -2, 0, 1, 0, 1, -1, -10, -30, -67, -138, -291,
                        -642, -1446, -3250};

  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  if(argc == 2) {
    int k;
    sscanf(argv[1], "%d", &k);
    int result = A(k, K(1), K(-1), K(-1), K(1), K(0));
    assert(result == TABLE[k]);
  };
  [pool drain];

  return EXIT_SUCCESS;
};
#include <cassert>
#include <iostream>
#include <tr1/functional> // I'm using tr1 because I have an old version of libstdc++
using namespace std;
using namespace std::tr1;

typedef function<int()> F;

int A(int k, const F &x1, const F &x2, const F &x3, const F &x4, const F &x5) {
  F B = [=, &k, &B] {
    return A(--k, B, x1, x2, x3, x4);
  };
  return k <= 0 ? x4() + x5() : B();
};

F L(int n) {
  return [n] {
    return n;
  };
};

int main(int argc, char **argv) {
  static int TABLE[] = {1, 0, -2, 0, 1, 0, 1, -1, -10, -30, -67, -138, -291,
                        -642, -1446, -3250};

  if(argc == 2) {
    int k;
    sscanf(argv[1], "%d", &k);
    int result = A(k, L(1), L(-1), L(-1), L(1), L(0));
    assert(result == TABLE[k]);
  };

  return EXIT_SUCCESS;
};
#导入
#导入,以防有人要检查。)

编辑:
如注释中所述,开销似乎来自
std::function
。如果有人需要,使用反而解决了问题,而且它比Objective-C快了一点,正如人们所期望的那样。

std::function
不建议用于性能关键型代码。只需使用普通lambda或模板。另请参见
trx
实现通常不会进行优化,我想是这样的,我用更新的libstdc++再次测试了它。随着人数的增加,增长速度仍在放缓。我要试着去掉std::function看看会发生什么!C++和Swift对优化的开启和否都非常敏感,Objto-C则更少。检查您的优化设置。@bolov:
std::function
用于将可调用类型擦除为普通可调用类型。这正是本案所需要的。