[Python] Converting a string of integers to a list of int - performance [duplicate]

Discussão em 'Python' iniciado por Stack, Abril 18, 2025.

  1. Stack

    Stack Membro Participativo

    Given a string S of whitespace delimited integers and needing to convert to a list of int, there are 2 common techniques.

    lst = list(map(int, S.split())) # method 1


    or

    lst = [int(n) for n in S.split()] # method 2


    To my surprise, I found that method 1 is faster than method 2 by a factor of ~9% (which I would argue is significant) whereas I would have expected little or no difference.

    Can someone please explain why method 1 is, apparently, more performant?

    Here's the test rig:

    from timeit import timeit
    from random import randint

    R = (1, 100_000)
    N = 10_000

    SNUMS = " ".join(str(randint(*R)) for _ in range(N))

    def pdiff(v1: float, v2: float) -> float:
    return (v1 - v2) / ((v1 + v2) / 2) * 100.

    def func1() -> list[int]:
    return list(map(int, SNUMS.split()))

    def func2() -> list[int]:
    return [int(n) for n in SNUMS.split()]

    assert func1() == func2()

    dx = (0.0, 0.0)

    for func in (func1, func2):
    d = timeit(lambda: func(), number=N)
    dx = (dx[1], d)
    print(func.__name__, f"{d:.4f}s")

    print(f"{pdiff(*dx):.2f}%")


    Output:

    func1 5.5540s
    func2 6.0766s
    -8.99%


    Platform:

    Python 3.13.3
    MacOS 15.4.1
    Apple M2

    Continue reading...

Compartilhe esta Página