schwartzian_transform.pl 808 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/perl
  2. # Performance comparison of Schwartzian transform.
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Schwartzian_transform
  5. use 5.010;
  6. use Benchmark qw(cmpthese);
  7. my @alpha = map { chr($_) } 32 .. 127;
  8. my @arr = (
  9. map {
  10. join('', map { $alpha[rand @alpha] } 1 .. 140)
  11. } 1 .. 100
  12. );
  13. cmpthese(
  14. -1,
  15. {
  16. schwartz => sub {
  17. my @sorted = map { $_->[1] }
  18. sort { $a->[0] cmp $b->[0] }
  19. map { [lc($_), $_] } @arr;
  20. @sorted;
  21. },
  22. without_schwartz => sub {
  23. my @sorted = sort { lc($a) cmp lc($b) } @arr;
  24. @sorted;
  25. },
  26. }
  27. );
  28. __END__
  29. Rate without_schwartz schwartz
  30. without_schwartz 4403/s -- -53%
  31. schwartz 9309/s 111% --