代码之家  ›  专栏  ›  技术社区  ›  Christian Geier

为什么repr(int)比str(int)快?

  •  33
  • Christian Geier  · 技术社区  · 8 年前

    我想知道为什么 repr(int) str(int) 。使用以下代码段:

    ROUNDS = 10000
    
    def concat_strings_str():
        return ''.join(map(str, range(ROUNDS)))
    
    def concat_strings_repr():
        return ''.join(map(repr, range(ROUNDS)))
    
    %timeit concat_strings_str()
    %timeit concat_strings_repr()
    

    我得到了这些计时(python 3.5.2,但与2.7.12的结果非常相似):

     1.9 ms ± 17.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
     1.38 ms ± 9.07 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    如果我走对了路, the same function long_to_decimal_string is getting called

    我是不是做错了什么,或者我还错过了什么?


    使现代化 这可能与 int __repr__ __str__ 方法不同 repr() str() int.__str__ int.__repr__ 实际上速度相当快:

    def concat_strings_str():
        return ''.join([one.__str__() for one in range(ROUNDS)])
    
    def concat_strings_repr():
        return ''.join([one.__repr__() for one in range(ROUNDS)])
    
    %timeit concat_strings_str()
    %timeit concat_strings_repr()
    

    结果:

    2.02 ms ± 24.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    2.05 ms ± 7.07 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    
    3 回复  |  直到 8 年前
        1
  •  35
  •   Dimitris Fasarakis Hilliard    8 年前

    因为使用 str(obj) 必须先通过 type.__call__ str.__new__ (create a new string) 然后 PyObject_Str (make a string out of the object) 它调用 int.__str__ 最后 ,使用链接的函数。

    repr(obj) ,对应于 builtin_repr ,直接呼叫 PyObject_Repr (get the object repr) int.__repr__ 使用与相同的功能 .

    call_function (处理 CALL_FUNCTION opcode 为呼叫生成的)是

    从GitHub上的主分支(CPython 3.7):

    正如您的更新所述,这与 vs int.__街__ ,它们毕竟是相同的函数;这都是关于如何 联系他们。 str公司

        2
  •  12
  •   Dimitris Fasarakis Hilliard    8 年前

    str repr 3.5分支中的实现。 看见 here .

    似乎有更多的登机手续 str公司 enter image description here

        3
  •  8
  •   MSeifert    8 年前

    有几种可能性,因为CPython函数负责 str repr 回报略有不同。

    但我想主要原因是 是一个 type (a类)和 str.__new__ __str__ 虽然 报告 __repr__