I was playing around with this a few ways in Python. I wondered if just passing through the characters once would be better than splitting and joining which passes through the words multiple times. First up, make a big string.
fromtimeimporttimea='hello this is my string it is lovely!'*10000a=a.strip()
The time... 0.0615s (3 s.f.). Now, although the first two pass through each character whereas the last one only passes through the words, surely split(' ') needs to examine each character to decide if it is ' ' or not? This got me thinking, so I tried:
A=''t=time()forcina:A+=cprint(time()-t)
Just going through the string and adding each character to the end of an new string takes 4.20s (3 s.f.) seconds! Compared with
t=time()A=''.join(cforcina)print(time()-t)
which takes 0.0246s.
In short, I conclude that split() and join() are magic and I will use them for building strings over += in Python from now on, where possible!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I was playing around with this a few ways in Python. I wondered if just passing through the characters once would be better than splitting and joining which passes through the words multiple times. First up, make a big string.
First try:
This takes 5.04s (3 s.f.). Maybe looking up the value of the string at
a[i-1]
is too slow, so here's another try using flags to speed things up:The time becomes 4.44s (3 s.f.), so we've shaved a bit off. Then I tried the Python equivalent of @jasterix solution:
The time... 0.0615s (3 s.f.). Now, although the first two pass through each character whereas the last one only passes through the words, surely
split(' ')
needs to examine each character to decide if it is' '
or not? This got me thinking, so I tried:Just going through the string and adding each character to the end of an new string takes 4.20s (3 s.f.) seconds! Compared with
which takes 0.0246s.
In short, I conclude that
split()
andjoin()
are magic and I will use them for building strings over+=
in Python from now on, where possible!