什么是有效的 - 在班级或n个领域的记录

时间:2015-09-07 16:47:07

标签: pascal freepascal

我有8字节字段的类。我可以将它们记录在一起并将记录放在1类字段中(记录是打包的并且有效)。

我有这个类的100000个对象。所以需要有效的变量 - 这是有效的,更少的内存:字节字段或记录字段?

它的FPC 2.6。

2 个答案:

答案 0 :(得分:2)

虽然FPC大师没有人没时间回答,但让我们探讨这个问题。以下是一些代码:

program Project1;

type
    TByteArray = packed array[Low(Word)..High(Word)] of Byte;
    PByteArray = ^TByteArray;

    TMyRec = packed record
        f1, f2, f3, f4, f5, f6, f7, f8: Byte;
    end;

    { TMyClass1 }

    TMyClass1 = class
        mark1: Byte;
        f1, f2, f3, f4, f5, f6, f7, f8: Byte;
        mark2: Byte;
        r: TMyRec;
        mark3: Byte;
        constructor Create;
        procedure ShowMe; // Dump of the object's data
    end;

{ TMyClass1 }

constructor TMyClass1.Create;
begin
    mark1 := 66;
    mark2 := 77;
    mark3 := 88;
end;

procedure TMyClass1.ShowMe;
var
    data: PByteArray;
    i: Word;
begin
    data := Pointer(Self);
    for i := 0 to 15 + 4 + 3 do // 4 - some unknown data at the beginning of the class, 3 - marks
        Writeln(data^[i]);
end;

var
    test: TMyClass1;
begin
    test := TMyClass1.Create;
    try
        test.ShowMe;
        Readln;
    finally
        test.Free;
    end;
end. 

输出是:

0
192
64
0
66 <- Data starts, simple fields
0
0
0
0
0
0
0
0
77 <- Second data portion, record
0
0
0
0
0
0
0
0
88 <- Data ends

正如我们在两种情况下都可以看到的,8个字段需要8个字节。

祝你好运。

答案 1 :(得分:1)

或者,如果您认为打包非常重要,只需声明包装类:

TMyClass1 = packed class
    mark1: Byte;
    f1, f2, f3, f4, f5, f6, f7, f8: Byte;
    mark2: Byte;
    r: TMyRec;
    mark3: Byte;
    constructor Create;
    procedure ShowMe; // Dump of the object's data
end;

类总是会有一些开销,但这不一定是字段的打包,而是隐藏的管理。随着时间的推移,开销变得越来越大。

但是100000条记录是花生。如果你浪费几个字节,它就像10MB左右,是现在最便宜的PC的一小部分内存。