Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Delphi: Общие вопросы > "Очистить" массив - как быстрее и правильнее


Автор: mspuz 1.3.2006, 12:39
Если есть массив, например из 100 элементов и его нужно обнулять при каждой итерации. Раньше я просто создавал цикл, в котором каждому элементу массива присваивал ноль. А недавно познакомился с функцией SetLength, что натолкнуло меня на мысль, а почему не сделать так:
SetLength(MyMas,0)
SetLength(MyMas,100)
По идеи должно сработать. Правильно ли это, быстрее ли это и вообще может существует другой, более рациональный подход

Автор: MBo 1.3.2006, 12:41
Лучше сделать FillChar (или ZeroMemory), а SetLength приводит к операциям перераспределения памяти.

Автор: Budy 1.3.2006, 12:42
SetLength - не какнает для Array'ев
А для обнуления лучше всего прогонять циклом и занулять

Автор: Snowy 1.3.2006, 12:52
MBo, именно так.
Кроме того, от SetLength память не занулится, а забъется мусором.

Автор: Демо 1.3.2006, 12:55
Цитата(Budy @ 1.3.2006, 12:42 Найти цитируемый пост)
SetLength - не какнает для Array'ев


С каких пор?
SetLength прекрасно можно использовать для динамических массивов.
Хотя, как указал MBo, это не самая быстрая операция. Быстрее просто чистить память.
Опять же, разовое перераспределение на небольших массивах не очень-то повлияет на скорость.

Автор: Yanis 1.3.2006, 12:57
Цитата(Snowy @ 1.3.2006, 12:52 Найти цитируемый пост)
Кроме того, от SetLength память не занулится, а забъется мусором.

С чего бы это?
Добавлено @ 13:00
При использовании SetLength новые элементы массива имеют значение 0. Разве нет?

Автор: Rennigth 1.3.2006, 13:18
Цитата(Демо @ 1.3.2006, 12:55 Найти цитируемый пост)
Хотя, как указал MBo, это не самая быстрая операция. Быстрее просто чистить память.

И чем она медленная?
Код

  Byte(s^[0]) := newLength;   // should also fill new space

Да, прохо что не залуляем память, а просто устанавливает длинну, но если это не критично, то она прикрастно подходит и быстрее.
Тем более после циклов все равно придеться длинну менять.



Автор: Демо 1.3.2006, 13:24
Цитата(Rennigth @ 1.3.2006, 13:18 Найти цитируемый пост)
Byte(s^[0]) := newLength;


Memory leak

Автор: Rennigth 1.3.2006, 13:26
Сорри для DynArray делфя вот это юзает:
Код

procedure _DynArraySetLength;
asm
{       PROCEDURE _DynArraySetLength(var a: dynarray; typeInfo: PDynArrayTypeInfo; dimCnt: Longint; lengthVec: ^Longint) }
{     ->EAX     Pointer to dynamic array (= pointer to pointer to heap object) }
{       EDX     Pointer to type info for the dynamic array                     }
{       ECX     number of dimensions                                           }
{       [ESP+4] dimensions                                                     }
        PUSH    ESP
        ADD     dword ptr [ESP],4
        CALL    DynArraySetLength
end;

но, сути не менят.

Автор: Snowy 1.3.2006, 13:30
Эт я погорячился.
Посмотрел реализацию SetLength...
Код
var
  i: Integer;
  newLength, oldLength, minLength: Longint;
  elSize: Longint;
  neededSize: Longint;
  p, pp: Pointer;
begin
  p := a;

  // Fetch the new length of the array in this dimension, and the old length
  newLength := PLongint(lengthVec)^;
  if newLength <= 0 then
  begin
    if newLength < 0 then
      Error(reRangeError);
    DynArrayClear(a, typeInfo);
    exit;
  end;

  oldLength := 0;
  if p <> nil then
  begin
    Dec(PLongint(p));
    oldLength := PLongint(p)^;
    Dec(PLongint(p));
  end;

  // Calculate the needed size of the heap object
  Inc(PChar(typeInfo), Length(PDynArrayTypeInfo(typeInfo).name));
  elSize := PDynArrayTypeInfo(typeInfo).elSize;
  if PDynArrayTypeInfo(typeInfo).elType <> nil then
    typeInfo := PDynArrayTypeInfo(typeInfo).elType^
  else
    typeInfo := nil;
  neededSize := newLength*elSize;
  if neededSize div newLength <> elSize then
    Error(reRangeError);
  Inc(neededSize, Sizeof(Longint)*2);

  // If the heap object isn't shared (ref count = 1), just resize it. Otherwise, we make a copy
  if (p = nil) or (PLongint(p)^ = 1) then
  begin
    pp := p;
    if (newLength < oldLength) and (typeInfo <> nil) then
      FinalizeArray(PChar(p) + Sizeof(Longint)*2 + newLength*elSize, typeInfo, oldLength - newLength);
    ReallocMem(pp, neededSize);
    p := pp;
  end
  else
  begin
    Dec(PLongint(p)^);
    GetMem(p, neededSize);
    minLength := oldLength;
    if minLength > newLength then
      minLength := newLength;
    if typeInfo <> nil then
    begin
      FillChar((PChar(p) + Sizeof(Longint)*2)^, minLength*elSize, 0);
      CopyArray(PChar(p) + Sizeof(Longint)*2, a, typeInfo, minLength)
    end
    else
      Move(PChar(a)^, (PChar(p) + Sizeof(Longint)*2)^, minLength*elSize);
  end;

  // The heap object will now have a ref count of 1 and the new length
  PLongint(p)^ := 1;
  Inc(PLongint(p));
  PLongint(p)^ := newLength;
  Inc(PLongint(p));

  // Set the new memory to all zero bits
  FillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0); // <<<<<<<<<<<<<<<<<

  // Take care of the inner dimensions, if any
  if dimCnt > 1 then
  begin
    Inc(lengthVec);
    Dec(dimCnt);
    for i := 0 to newLength-1 do
      DynArraySetLength(PPointerArray(p)[i], typeInfo, dimCnt, lengthVec);
  end;
  a := p;
end;
Она зануляет память
Добавлено @ 13:31
Но что-то мне говорит, что просто FillChar будет работать немножко быстрее smile

Автор: Rennigth 1.3.2006, 13:39
Snowy,
а эт ты где такое нашел?, у тя какая Делфя, у мя 6-ка.
Добавлено @ 13:43
Вопрос отпал smile -> DynArraySetLength, недосмотрел.

Автор: Yanis 1.3.2006, 14:12
Цитата(Rennigth @ 1.3.2006, 13:39 Найти цитируемый пост)
а эт ты где такое нашел?, у тя какая Делфя, у мя 6-ка.

В это в Delphi 7.

Автор: Budy 2.3.2006, 06:06
Демо, smile видать ошибся, прошу прощения

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)