4x run-time improvement to string generator
4x run-time improvement to string generator

closes #19

Motvation

@Ana06 brought up slow generation of random strings. The existing
implementation incurs Array resizing and string manipulation.

Solution

Avoid Array resizing by initializing Array to the known size. Use
Array#sample (written in C) instead of computing a random index.

The results are about a 4x speed increase when generating strings.

Benchmark test follows:

    #!/usr/bin/env ruby
    require 'benchmark/ips'
    require 'rantly'

    class Rantly

      def string2(char_class=:print)
	chars = case char_class
		when Regexp
		  Chars.of(char_class)
		when Symbol
		  Chars::CLASSES[char_class]
		end
	raise "bad arg" unless chars

	char_strings = chars.map { |c| c.chr }
	str = Array.new(size)
	current_index = 0
	while current_index < size
	  str[current_index] = char_strings.sample
	  current_index += 1
	end
	str.join
      end
    end

    [1000, 10_000, 100_000, 1_000_000].each do |size|
      Benchmark::ips do |bm|

	bm.report("rantly #{size}") do
	  Rantly { sized(size) { string } }
	end

	bm.report("range sample #{size}") do
	  Rantly { sized(size) { string2 } }
	end

	bm.compare!
      end
    end

abargnesi/rantly,Ana06/rantly