Snippets

Stefan Glienke Case of on string proposal

Created by Stefan Glienke last modified
program StringCase;

{$APPTYPE CONSOLE}

uses
  Diagnostics,
  StrUtils;

function IndexOf(const AText: string; const AValues: array of string): Integer;
var
  i: Integer;
begin
  for i := Low(AValues) to High(AValues) do
    if AText = AValues[i] then
      Exit(i);
  Result := -1;
end;

const
  count = 1000000;
  values: array[0..2] of string = ('a', 'b', 'c');
var
  s: string;
  sw: TStopwatch;
  i: Integer;
begin
  s := 'a';

(*
  case s of
    'a': Writeln('x');
    'b': Writeln('y');
    'c': Writeln('z');
  end;
*)

  sw := TStopwatch.StartNew;
  for i := 1 to count do
  case IndexStr(s, values) of
    0: ;//Writeln('x');
    1: Writeln('y');
    2: Writeln('z');
  end;
  Writeln(sw.ElapsedMilliseconds);

  sw := TStopwatch.StartNew;
  for i := 1 to count do
  case IndexOf(s, values) of
    0: ;//Writeln('x');
    1: Writeln('y');
    2: Writeln('z');
  end;
  Writeln(sw.ElapsedMilliseconds);
  Readln;
end.

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.