Ticket #134 (closed enhancement: fixed)
Optimization: Make "key in dict.keys" fast
Reported by: | Chuck | Owned by: | Chuck |
---|---|---|---|
Priority: | minor | Milestone: | |
Component: | Cobra Compiler | Version: | 0.8.0 |
Keywords: | optimization | Cc: |
Description
Writing:
if key in dict.keys, ...
is fairly natural, but about 15 X slower than:
if dict.containsKey(key), ...
According to this program:
use System.Diagnostics class X def main is shared d = Dictionary<of String, bool>() for c in 'abcdefghijklmnopqrstuvwxyz' d[c.toString] = false key = 'k' count = 1_000_000 sw = Stopwatch() sw.start for i in count b = d.containsKey(key) b = d.containsKey(key) b = d.containsKey(key) b = d.containsKey(key) b = d.containsKey(key) sw.stop t1 = sw.elapsedMilliseconds print 'containsKey:', t1 sw.reset sw.start for i in count b = key in d.keys b = key in d.keys b = key in d.keys b = key in d.keys b = key in d.keys sw.stop t2 = sw.elapsedMilliseconds print 'key in d.keys:', t2 print t2 / t1, ' X slower' ct_trace d.keys CobraCore.noOp(b)
That will vary since the culprit is the linear search.
Make the in-based expression just as fast by transforming it to the containsKey expression.
Change History
Note: See
TracTickets for help on using
tickets.