Hello --

On Thu, 28 Dec 2000, Robert Feldt wrote:

> Hi,
> 
> I need to convert large strings to valid C char arrays. A naive way goes
> through the string while appending "#{str[i]}," to an output string but
> this (of course) doesn't scale well. I tried:
> 
[...]
> 
> but it still takes a long time (about 40 kB/s on my 366 Mhz laptop).
> 
> Is there a faster/better way?

   def mine(str, aname = nil)
     nums = str.unpack('c*').join(',')
     nums = 
      "const char #{aname}[#{str.length}] = {" + nums + "}" if aname
     nums
   end

(unless unpack introduces non-portable issues of storage size (?)  But
I don't think so.)

Anyway, it's certainly faster:


   $string = "this is a string"
   n = 5000

   bm do |x|
     x.report { n.times do yours($string, "aname")  end}
     x.report { n.times do mine($string, "aname")  end}
   end

	user     system      total        real
   15.530000   0.010000  15.540000 ( 15.644752)
    3.850000   0.000000   3.850000 (  3.857197)


(This test has been checked for First Report Time-Distension
Syndrome :-)


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav