Re: A stack with better performance than using a list

Alex Willmer <[email protected]>
Newsgroups gmane.comp.python.org.uk
Message-ID <CABv=ZQFqK+AeMpVDYuahFmO_zEPCD2wZVBd8dyNhwEdBRxhZ_g@mail.gmail.com>
On 7 June 2017 at 18:50, Jonathan Hartley <[email protected]> wrote:
> Ah. In writing this out, I have begun to suspect that my slicing of 'tokens'
> to produce 'args' in the dispatch is needlessly wasting time. Not much, but
> some.

To put some numbers out there, eliminating the slice is not always a
win. On Python 2.7.13 Jonathon's dispatch() is marginally faster for
len(line.split()) == 10. The break even is around 40. At 1000 and
above dispatch_1() is approx 25% faster. Same code on Python 3.6.1 was
approx the same speed (within 10%).
class Bench:
    def foo(self): pass

    def dispatch(self, line):
        tokens = line.split()
        method = getattr(self, tokens[0])
        args = tokens[1:]
        #method(*args)

    def dispatch_1(self, line):
        op, rest = line.split(None, 1)
        method = getattr(self, op)
        args = rest.split()
        #method(*args)

python --version
Python 2.7.13

python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*10"
"b.dispatch(s)"
1000000 loops, best of 3: 0.577 usec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*10"
"b.dispatch_1(s)"
1000000 loops, best of 3: 0.673 usec per loop

python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*1000"
"b.dispatch(s)"
100000 loops, best of 3: 19.1 usec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ ' x'*1000"
"b.dispatch_1(s)"
100000 loops, best of 3: 14.8 usec per loop

python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ '
x'*1000000" "b.dispatch(s)"
100 loops, best of 3: 16.9 msec per loop
python -mtimeit -s "import bench; b=bench.Bench(); s='foo'+ '
x'*1000000" "b.dispatch_1(s)"
100 loops, best of 3: 12.4 msec per loop
-- 
Alex Willmer <[email protected]>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.