C:这是更快,访问全局变量或传递函数指针 [英] C: Which is faster, accessing global variable or passing a pointer to the function

查看:503
本文介绍了C:这是更快,访问全局变量或传递函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在重写我的节目之一。它有一个严重的递归函数解决了PEG-纸牌:

I am currently rewriting one of my programs. It has a heavily recursive function which solves peg-solitaire:

int solve(int draw) {
  if (finished())
    return true;

  //loop over every possible move (about 76 long values)
  //do a move (access the board, which is a long value)
  if (solve(draw + 1))
    return true;

  return false;
}

所以我在想,如果它是更快地使用解决这样的:

So i was wondering if it's faster to use solve like this:

solve(int draw, long **moves, long *board) {}

目前,这两项举措和电路板都是全局变量。

At the moment both moves and board are global variables.

当然我要去测试它,但如果有人告诉我,这种尝试是不会有效率,我会节省一些时间。)

Of course i am going to test it, but if someone tells me that this attempt isn't going to be efficient i will save some time :).

问候

推荐答案

它可能不会被视为有效,但肯定知道的唯一方法是分析您的code。如果您执行的大部分时间都花在做你的实际的游戏逻辑,那么开销放入几个参数堆栈上的微小的量是微乎其微的。

It probably won't be as efficient, but the only way to know for sure is to profile your code. If the bulk of your execution time is spent doing your actual game logic, then the tiny amount of overhead putting a few arguments on the stack should be negligible.

不过,从设计的角度来看,避免了全局变量要好得多。它可以让你的code是无状态的,因此有可能重入和线程安全的。然而,这可能会或可能不相关的应用程序。

However, from a design point of view, avoiding global variables is much better. It allows your code to be stateless, and hence potentially re-entrant and thread-safe. However, this may or may not be relevant for your application.

这篇关于C:这是更快,访问全局变量或传递函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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