While we have loads of computation power & memory available today, I think as a professional it is better to code quicker than slower, unless it makes code unclear.
In the posted Vigenere code . . .
- String memory allocation/re-allocation is slow so avoid ConCat(), String + String (even though its quicker than ConCat), and Delete(). Better to SetLength for strings and use index accessing for characters.
- Use 'for' loops rather than 'while' loops.
- Reduce the code for every character. Check for bEncrypt before entering repeated similar code in a 'for' loop for each character action.
- IMO sTable should be initialised before use by := '' or SetLength(). AIUI variables in functions are not zeroed, and you might be using garbage.
- Crypt by re-referencing the key as given rather that using multiple keys up to the source length.
function Vigenere(Src, Key : string; Encrypt : boolean) : string; const OrdMinChar : integer = Ord('A'); OrdMaxChar : integer = Ord('Z'); IncludeChars : set of char = ['A'..'Z']; var CharRangeCount, i, j, KeyLen, KeyInc, SrcOrd, CryptOrd : integer; SrcA : string; begin CharRangeCount := OrdMaxChar - OrdMinChar + 1; KeyLen := Length(Key); SetLength(SrcA, Length(Src)); If Encrypt then begin // transfer only included characters to SrcA for encryption j := 1; for i := 1 to Length(Src) do begin if (Src[i] in IncludeChars) then begin SrcA[j] := Src[i]; inc(j); end; end; SetLength(SrcA, j - 1); end; SetLength(Result, Length(SrcA)); if Encrypt then begin // Encrypt to Result for i := 1 to Length(SrcA) do begin SrcOrd := Ord(Src[i]) - OrdMinChar; KeyInc := Ord(Key[((i - 1 ) mod KeyLen)+ 1]) - OrdMinChar; CryptOrd := ((SrcOrd + KeyInc) mod CharRangeCount) + OrdMinChar; Result[i] := Char(CryptOrd); end; end; else begin // Decrypt to Result for i := 1 to Length(SrcA) do begin SrcOrd := Ord(Src[i]) - OrdMinChar; KeyInc := Ord(Key[((i - 1 ) mod KeyLen)+ 1]) - OrdMinChar; CryptOrd := ((SrcOrd - KeyInc + CharRangeCount) mod CharRangeCount) + OrdMinChar; // KeyInc may be larger than SrcOrd Result[i] := Char(CryptOrd); end; end; end;