Why are mutable strings slower than immutable strings?

Why are mutable strings slower than immutable?

EDIT:

>>> import UserString
... def test():
...     s = UserString.MutableString('Python')
...     for i in range(3):
...         s[0] = 'a'
... 
... if __name__=='__main__':
...     from timeit import Timer
...     t = Timer("test()", "from __main__ import test")
...     print t.timeit()
13.5236170292



>>> import UserString
... def test():
...     s = UserString.MutableString('Python')
...     s = 'abcd'
...     for i in range(3):
...         s = 'a' + s[1:]
... 
... if __name__=='__main__':
...     from timeit import Timer
...     t = Timer("test()", "from __main__ import test")
...     print t.timeit()
6.24725079536


>>> import UserString
... def test():
...     s = UserString.MutableString('Python')
...     for i in range(3):
...         s = 'a' + s[1:]
... 
... if __name__=='__main__':
...     from timeit import Timer
...     t = Timer("test()", "from __main__ import test")
...     print t.timeit()
38.6385951042

I think it is obvious why I set s = UserString.MutableString ('Python') in the second test.

+3
source share
4 answers

, , , ( - , Python Java , , , , ;-), - - , ++, std::string const std::string, ( , , , , , ; -).

Java Python. , , , ( ) - Python, ( ) " ". " ", - , . Python "" () , . , , , .

, , , . , , - ( ), , . Python , , , , "" , , , , ( , - , ).

- , , (, , , , ++ , , , , ). (, , , ;), , Java Python, - - ( Python, , , , , , - -.)

+22

, , , / . .

, , , ( ), , CPU.

, googling, :

, -

+3

, python . , ( ). , , . , .

, , (malloc ), , , , , .

, python . , , .

, , . , :

s = 'a'
d = {s : 1}
s = s + 'b'
d[s] = ?

, python , dicts , , - , dict. , - python / dict, . .

+3

, C, MutableString Python.

Python, - . UserString.py Python.

Python:

:

UserString . , Python , Python 2.2, , str- UserString ( MutableString).

This module defines a class that acts as a wrapper around string objects. This is a useful base class for your own string classes that can inherit from them and override existing methods or add new ones. In this case, you can add new behavior to the rows.

It should be noted that these classes are extremely inefficient in comparison with real strings or Unicode objects; this is especially the case with MutableString.

(Added emphasis).

+1
source

Source: https://habr.com/ru/post/1763282/


All Articles