Skip to content

Commit 00db22d

Browse files
committed
pre-allocate those records within my dictionary, as initially done
1 parent 9d47171 commit 00db22d

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

entries/ghatem-fpc/src/onebrc.pas

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,13 @@ function RoundExDouble(const ATemp: Double): Double; inline;
3535
TMyDictionary = class
3636
private
3737
FHashes: TKeys;
38-
FData : TValues;
38+
FValues: TValues;
39+
FRecords: array of TStationData;
3940
procedure InternalFind(const aKey: Cardinal; out aFound: Boolean; out aIndex: Integer);
4041
public
4142
constructor Create;
4243
property Keys: TKeys read FHashes;
43-
property Values: TValues read FData;
44+
property Values: TValues read FValues;
4445
function TryGetValue (const aKey: Cardinal; out aValue: PStationData): Boolean; inline;
4546
procedure Add (const aKey: Cardinal; const aValue: PStationData); inline;
4647
end;
@@ -169,21 +170,24 @@ procedure TMyDictionary.InternalFind(const aKey: Cardinal; out aFound: Boolean;
169170
end;
170171

171172
constructor TMyDictionary.Create;
173+
var
174+
I: Integer;
172175
begin
173176
SetLength (FHashes, cDictSize);
174-
SetLength (FData, cDictSize);
177+
SetLength (FValues, cDictSize);
178+
SetLength (FRecords, cDictSize);
179+
180+
for I := 0 to cDictSize - 1 do begin
181+
FValues[I] := @FRecords[I];
182+
end;
175183
end;
176184

177185
function TMyDictionary.TryGetValue(const aKey: Cardinal; out aValue: PStationData): Boolean;
178186
var
179187
vIdx: Integer;
180188
begin
181189
InternalFind (aKey, Result, vIdx);
182-
183-
if Result then
184-
aValue := FData[vIdx]
185-
else
186-
aValue := nil;
190+
aValue := FValues[vIdx];
187191
end;
188192

189193
procedure TMyDictionary.Add(const aKey: Cardinal; const aValue: PStationData);
@@ -194,7 +198,7 @@ procedure TMyDictionary.Add(const aKey: Cardinal; const aValue: PStationData);
194198
InternalFind (aKey, vFound, vIdx);
195199
if not vFound then begin
196200
FHashes[vIdx] := aKey;
197-
FData[vIdx] := aValue;
201+
FValues[vIdx] := aValue;
198202
end
199203
else
200204
raise Exception.Create ('TMyDict: cannot add, duplicate key');
@@ -351,7 +355,6 @@ procedure TOneBRC.ProcessData (aThreadNb: UInt16; aStartIdx: Int64; aEndIdx: Int
351355
SetString(vStation, pAnsiChar(@FData[vLineStart]), vLenStationName);
352356

353357
// pre-allocated array of records instead of on-the-go allocation
354-
new(vData);
355358
vData^.Min := vTemp;
356359
vData^.Max := vTemp;
357360
vData^.Sum := vTemp;
@@ -421,7 +424,7 @@ procedure TOneBRC.GenerateOutput;
421424
vStations.BeginUpdate;
422425
for vData in FStationsDicts[0].Values do begin
423426
// nil value means empty slot: skip
424-
if vData <> nil then
427+
if vData^.Count <> 0 then
425428
vStations.Add(vData^.Name);
426429
end;
427430
vStations.EndUpdate;

0 commit comments

Comments
 (0)