55 | | |
| 55 | ---- |
| 56 | {{{ |
| 57 | dict.get("x") |
| 58 | }}} |
| 59 | is significantly slower than |
| 60 | {{{ |
| 61 | dict["x"] |
| 62 | }}} |
| 63 | |
| 64 | but...the construction: |
| 65 | {{{ |
| 66 | y = dict.get("x", None) |
| 67 | if y: |
| 68 | }}} |
| 69 | is as fast as |
| 70 | {{{ |
| 71 | if x in dict: |
| 72 | y = dict["x"] |
| 73 | }}} |
| 74 | |
| 75 | Also, keys() is slowing things down. |
| 76 | {{{ |
| 77 | if a in dict.keys() |
| 78 | }}} |
| 79 | is ~25% slower than: |
| 80 | {{{ |
| 81 | if a in dict |
| 82 | }}} |
| 83 | |
| 84 | Another thing is that the profiler showed that there is extensive use of |
| 85 | isinstance. So I tried to find an alternative, which would be: |
| 86 | {{{ |
| 87 | if type(x) == "yyy" |
| 88 | }}} |
| 89 | In fact, this is ~30% faster than isinstance, but it won't find subclasses. |
| 90 | So, if you test for: |
| 91 | {{{ |
| 92 | if isinstance(x, dict) |
| 93 | }}} |
| 94 | and want Storages to match, then you cannot replace isinstance. |
| 95 | |
| 96 | A real killer is hasattr(). |
| 97 | I ran 5 million loops of |
| 98 | {{{ |
| 99 | if "a" in dict: |
| 100 | }}} |
| 101 | vs. |
| 102 | {{{ |
| 103 | if hasattr(dict, "a") |
| 104 | }}} |
| 105 | which was 4.5s vs. 12s. |
| 106 | |
| 107 | Hence - for dicts, avoid hasattr to test for containment. |
| 108 | ---- |