擅长:python、mysql、java
<p>将一个456574位数字转换成一个字符串并非没有成本;这是一个<em>大</em>字符串,将近50万个字符几乎是半兆字节的内存(在OS X系统上,使用Python 2.7):</p>
<pre><code>>>> import math
>>> import sys
>>> p = math.factorial(100000)
>>> p_str = str(p)
>>> sys.getsizeof(p_str) # memory footprint in bytes
456611
>>> 456611 / 1024.0 / 1024.0 # memory footprint in megabytes
0.4354581832885742
</code></pre>
<p>Python需要一点时间来生成该字符串,操作系统需要分配所需的内存:</p>
<pre><code>>>> from timeit import timeit
>>> timeit('str(p)', 'from __main__ import p', number=10) # convert to a string, 10 times
25.308346033096313
</code></pre>
<p>因此,平均需要2.5秒才能将这些数字转换成字符串。如果您实际复制并粘贴了所有这些数字(而不是像我那样使用变量),那么您还需要添加更多的时间,因为Python必须解析int文本,并在转换为字符串之前首先生成integer对象。你知道吗</p>
<p>您无法将其与长度为1(<code>'p'</code>)的字符串进行比较,后者只占用几个字节的内存(在我的系统中为38字节)。你知道吗</p>