在python中反转字符串的最快方法

问题描述:

我想出了两种不同的方法来反转 Python 中的字符串.

I was able to come up with two different ways to reverse a string in Python.

常识表明,代码行数越多,运行速度就越慢.

Commonsense dictates that the more lines of code the slower it runs.

我做了以下几行代码:

代码1

"".join(reversed(map(lambda x:x,st)))

代码 2

st[::-1]

这些提供了类似的性能.对于一个 20000 长的字符串,我什至看不到性能上的差异.

These give similar performance. For a 20000 long string I am not able to see a difference of even a millisecond in performance.

我认为第一个应该是一种较慢的方法,因为它执行的操作多 3 倍.

I think the first one should be a slower approach because it performs 3x more operations.

问题

为什么我没有看到性能差异?

Why am I not seeing a performance difference?

我看到了不同之处.

首先,map(lambda x: x, st) 是怎么回事?目的是什么?

First of all, what is up with map(lambda x: x, st)? What is the purpose?

使用 timeit 模块来测试您的代码:

Use the timeit module to test your code:

$ python -m timeit '"".join(reversed("abcdefghijklmnopqrstuvwxyz"))'
1000000 loops, best of 3: 0.586 usec per loop
$ python -m timeit '"abcdefghijklmnopqrstuvwxyz"[::-1]'           
10000000 loops, best of 3: 0.0715 usec per loop

如您所见,对于此特定输入,切片在我的机器上快了约 8 倍.也更简洁.

As you can see, the slice is ~8x faster on my machine for this particular input. It's also more concise.