String Concatenation Extreme-Slowdown Issue

Monkey Forums/Monkey Programming/String Concatenation Extreme-Slowdown Issue

ElectricBoogaloo(Posted 2013) [#1]
If KeyHit(KEY_UP)
Local ftxta$=""
Local ftxtb$=""
Local Start=Millisecs()

	For m=0 To 499
	For n=0 To 499
		ftxta=ftxta+"123"
	Next
	ftxtb=ftxtb+ftxta
	ftxta=""
	Next
Print "Up Long : "+ftxtb.Length()
Print "Time Taken : "+(Millisecs()-Start)
Endif

If KeyHit(KEY_DOWN)
Local ftxta$=""
Local ftxtb$=""
Local Start=Millisecs()

	For m=0 To 249999
		ftxta=ftxta+"123"	
	Next
Print "Down Long : "+ftxta.Length()
Print "Time Taken : "+(Millisecs()-Start)
Endif


Tip : Try UP first, because when Down stalls, it can take quite a while to recover!

HTML5 doesn't care..
Android seems dependent on the device.

But GLFW .. WOW!!!!

Keep in mind, both versions do EXACTLY THE SAME THING, except that the strings are fitted together in very slightly different ways.


Gerry Quinn(Posted 2013) [#2]
Patient: "Doctor, it hurts when I do this!"

Doctor: "Then stop doing that!"


ElectricBoogaloo(Posted 2013) [#3]
I'm going to assume that's a GP.
GP's tend to find the quick fix, then ignore the actual fundamental problem.

Example

Patient: "Doctor, my neck is sore."
Doctor: "What do you do all day?"
Patient: "I sit at a computer and write a new game every single week."
Doctor: "Well then, that's your problem. You must be sitting badly. Try a different chair."

Year Two
Patient: "Doctor, my neck is still sore and is getting worse."
Doctor: "What do you do all day?"
Patient: "I still sit at a computer and write a new game every single week."
Doctor: "Well then, that's still your problem. Have you tried a different desk?"

Year Three
Patient: "Doctor, seriously, my neck is still sore."
Doctor: "...?"
Patient: ".. Yes.. I still sit at a computer and write a new game every single week."
Doctor: "Dur!!!"

A Month Later
Patient: "Hello Mr Ambulance driver. I've been vomitting blood!"
Mr Ambulance Driver: "Holy Monkeys. Your bloody pressure's completely off the scale!"

Later that day
Proper Doctor: "Brain Tumour!!"


Bloody GPs. Bunch of idiots..


Nobuyuki(Posted 2013) [#4]
Strings are immutable in Monkey, so when you concat a string, you're actually creating a new one and ditching the old one. GC will be invoked on all targets, eventually, and the penalty depends on the target. This is why you should avoid large concats wherever possible!

I found the first reply amusing, and it might actually be good advice. Does this happen when building the string using a stack or array from chars?


marksibly(Posted 2013) [#5]
I recommend the use of a StringStack to efficiently 'build' strings like this, eg:

Local buf:=New StringStack
For Local i:=0 Until whatever
   buf.Push GetAString()
Next
Local result:=buf.Join()