0

我最近写了一些代码,它使用相同的无符号 short 来存储两个值,一个结果和一个 id,例如:

unsigned short data = new_id();
// result is either 0 or 1 so store it in the rightmost bit and move the id left
data = (data << 1) + get_result();
// ... later ...
// now we can print results like
printf("%u: %u\n", data & 1, data >> 1);

只使用结构来保存两个值会更好,还是这种类型的东西常见/可接受?该程序已经存储了如此多的内存,我想我会开始寻找减少它使用的内存的方法。

4

8 回答 8

13

位域(但前提是你真的需要空间紧张——即嵌入式系统)?

typedef struct id_result {
    unsigned int id : 15;
    unsigned int result : 1;
} id_result;

否则,是的,使用具有更完整和更有意义定义的结构:

typedef uint16 IDTYPE; /* assuming uint16 exists elsewhere */

typedef struct id_result {
    IDTYPE id;
    bool result;
} id_result;
于 2009-12-03T16:13:56.633 回答
7

除非内存非常紧张,否则我会走 struct 路线。对于下一个必须维护您的代码的人来说,这种方式更清晰,也更容易。

我想起了 M68000 有 32 位地址寄存器但实际上只使用了 24 位的时候。程序员进行了各种“优化”以将信息存储在其他 8 位中。当更高版本的芯片(如 M68030)使用全部 32 位时,男孩的脸都红了。

于 2009-12-03T16:12:44.920 回答
2

To those who advise against conserving memory with bitfields: as the years go by and computers get more gigabytes, L1$ (the fast memory) remains just a few dozen kilobytes. For most applications today, a majority of time is spent waiting for slow memory to arrive in the L1$.

Since slow memory is the bottleneck in most applications, conserving memory with bitfields can actually significantly increase an application's speed. This wasn't as true twenty years ago.

于 2009-12-03T20:32:11.653 回答
2

除非内存绝对紧缩,否则我宁愿采用具有两个不同变量的结构的更简单方法。它增加了可读性并减少了维护工作。

于 2009-12-03T16:14:06.260 回答
2

如果这样做仅仅是为了减少内存使用,那么我相信你不应该这样做。您最好使用带有 2 个短裤的结构,这会使代码更具可读性。与使代码更易于维护所获得的好处相比,这样做所节省的内存量非常小。

我建议您首先对系统进行分析,以了解是否存在任何内存泄漏或是否有人不必要地分配了大块内存等,然后尝试解决该问题。如果还是找不到解决办法,那就找出程序的哪一部分占用了大部分内存,并尝试重新设计它的内存分配模型。

于 2009-12-03T16:17:43.930 回答
1

在我看来,自己将两条短裤装进一条短裤比使用结构体更费力且更容易出错。如果确实需要使用更少的内存,您可以使用 struct 指定位域:

struct myStruct {
int data:8;
int result:8;
};

它实现了相同的内存减少结果,同时提高了代码的整体可维护性。

于 2009-12-03T16:16:22.277 回答
0

带有位域的结构是最容易理解的实现。如果您不使用这种方法,则可以使用一组文档齐全的 ,将值对打包和解包到 16 位值中。

于 2009-12-03T20:39:24.937 回答
0

使用结构/对象不一定是最好或最清晰的方法。

假设您有一组简单的整数数据点,但它们可以被删除或标记为无效,如果您只是使用 MSB 将其标记为“不使用”,那么您需要添加到算法中的只是一个

if ( item > 0 )
   item += blah

但是如果你有一个结构,那么现在的每一点算术都需要一个成员访问

if ( item.valid() ) 
   item.setValue(item.getValue() + blah);
于 2009-12-03T20:47:15.663 回答