Caching eval() for reuse to gain performance ?

N

Neville Burnell

------_=_NextPart_001_01C57ADF.00F25475
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: quoted-printable

Hi,

I have an active record collection and I need to 'eval' a string against
each row from the collection. Instead of processing the 'eval' for each
row, I was thinking to 'cache' the eval into a Proc to for reuse, ie:

irb(main):001:0> @a =3D 1
=3D> 1
irb(main):002:0> @b =3D 7
=3D> 7
irb(main):003:0> c =3D %q{ @a + @b }
=3D> " @a + @b "
irb(main):004:0> d =3D Proc.new { eval c }
=3D> #<Proc:0x02ad1240@(irb):4>
irb(main):005:0> d.call
=3D> 8
irb(main):006:0> @a =3D 2
=3D> 2
irb(main):007:0> d.call
=3D> 9
irb(main):008:0>

Is my assumption that eval is relatively expensive, and that a Proc call
is fast correct?
Any suggestions on how to do this better?

Thanks=20

Nev

------_=_NextPart_001_01C57ADF.00F25475--
 
K

Kent Sibilev

I might be wrong here, but I think you proc method is not faster or
it's even slower than plain eval method. Every time you call a proc,
eval gets called as well.

You can try to define your proc like so:

p =3D eval "lambda{#{c}}"

Kent.
 
A

Adam Sanderson

That won't gain you any effiecency. Assuming that you're doing the
same statement for each record perhaps you'd be better off with
something along the lines of:

irb(main):001:0> p = proc{|a,b| a+b }
=> #<Proc:0x000583ec@(irb):1>
irb(main):002:0> p.call(1,5)
=> 6

You might just need to rethink your approach a little.
.adam sanderson
 
K

Kent Sibilev

Care to explain? The idea was that you don't know beforehand what code
gets called by proc.

I don't like both approaches, but:

$ cat eval_cache.rb
require 'benchmark'

c =3D '@a + @b'
@a, @b =3D 1, 2
p1 =3D lambda { eval c }
p2 =3D eval "lambda { #{c} }"

Benchmark.bm do |x|
x.report do
100000.times {p1.call}
end
x.report do
100000.times {p2.call}
end
end
$ ruby eval_cache.rb

user system total real
0.480000 0.000000 0.480000 ( 0.480000)
0.160000 0.000000 0.160000 ( 0.161000)

Kent.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,276
Latest member
Sawatmakal

Latest Threads

Top