Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Python string class like StringBuilder in C#?

Python string class like StringBuilder in C#?

August 20, 2021 by James Palmer

There is no one-to-one correlation. For a really good article please see Efficient String Concatenation in Python:

Building long strings in the Python
progamming language can sometimes
result in very slow running code. In
this article I investigate the
computational performance of various
string concatenation methods.

TLDR the fastest method is below. It’s extremely compact, and also pretty understandable:
def method6():
return ”.join([`num` for num in xrange(loop_count)])

Relying on compiler optimizations is fragile. The benchmarks linked in the accepted answer and numbers given by Antoine-tran are not to be trusted. Andrew Hare makes the mistake of including a call to repr in his methods. That slows all the methods equally but obscures the real penalty in constructing the string.
Use join. It’s very fast and more robust.
$ ipython3
Python 3.5.1 (default, Mar 2 2016, 03:38:02)
IPython 4.1.2 — An enhanced Interactive Python.

In [1]: values = [str(num) for num in range(int(1e3))]

In [2]: %%timeit
…: ”.join(values)
…:
100000 loops, best of 3: 7.37 µs per loop

In [3]: %%timeit
…: result = ”
…: for value in values:
…: result += value
…:
10000 loops, best of 3: 82.8 µs per loop

In [4]: import io

In [5]: %%timeit
…: writer = io.StringIO()
…: for value in values:
…: writer.write(value)
…: writer.getvalue()
…:
10000 loops, best of 3: 81.8 µs per loop

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in