RingDotNetfor Ring

Speed — measure first

Programs get faster when you measure, not when you guess. This lesson times code with a Stopwatch, compares two ways of building text, adds a cache, and shows the cost of calls across the bridge.

What you will learn#

The rules of speed#

  1. Make it work, then make it right, then make it fast — and only if it is too slow.
  2. Measure. The slow part is rarely the part you suspect.
  3. The biggest wins come from doing less work (a cache, a better algorithm, fewer calls), not from clever tricks.

The program#

samples/UsingDotNet/tutorials/ch06_speed.ring
# speed - measure first, then choose: Stopwatch, StringBuilder, a cache (memoization) and fewer calls
load "dotnet.ring"

using {
	"System"
	"System.Diagnostics"
	"System.Text"
	"System.Collections.Generic"
}

nCalls = 0
nCachedCalls = 0
aCache = []

func main

	# 1. Measure with a Stopwatch. A guess about speed is often wrong.
	oWatch = new Stopwatch()
	oWatch.Start()
	nSum = 0
	for nI = 1 to 200000
		nSum += nI
	next
	oWatch.Stop()
	? "1. A loop of 200000 additions gives " + nSum + " (measured: " + (oWatch.ElapsedMilliseconds >= 0) + ")"

	# 2. Building a big text: Ring's own += against the .NET StringBuilder. In other languages the builder always wins; here every
	#    Append is a call over the bridge, so do not assume - measure.
	nTextTime = timeOf(:buildWithPlus)
	nBuilderTime = timeOf(:buildWithBuilder)
	? nl + "2. Same text (20000 pieces), two ways:"
	if nBuilderTime < nTextTime
		? "   the faster one: StringBuilder"
	else
		? "   the faster one: Ring's own +="
	ok
	? "   same result? " + yesNo(len(buildWithPlus(0)) = len(buildWithBuilder(0)))

	# 3. A cache (memoization): never compute the same thing twice. Fibonacci is the classic example.
	nSlow = timeOf(:fibSlow)
	nFast = timeOf(:fibCached)
	? nl + "3. fib(22): slow = " + fibSlow(22) + ", cached = " + fibCached(22)
	? "   Number of calls without a cache: " + nCalls + ", with a cache: " + nCachedCalls
	? "   the cached version is faster ? " + yesNo(nFast < nSlow)

	# 4. Fewer calls across the bridge: each .NET call has a small cost. Ask once for a list instead of 1000 times for one item.
	oList = new StringList()
	for nI = 1 to 500
		oList.Add("item" + nI)
	next
	nOne = timeOfItems(oList,False)
	nAll = timeOfItems(oList,True)
	? nl + "4. Reading 500 items: one by one over the bridge vs one call (ToList)"
	? "   one call is faster ? " + yesNo(nAll < nOne)

func timeOf cFunction

	oWatch = new Stopwatch()
	oWatch.Start()
	eval(cFunction + "(22)")
	oWatch.Stop()
	return oWatch.Elapsed.TotalMilliseconds

func timeOfItems oList, lAtOnce

	oWatch = new Stopwatch()
	oWatch.Start()
	nTotal = 0
	for nRound = 1 to 5
		if lAtOnce
			aItems = oList.ToList()
			nTotal += len(aItems)
		else
			for nIndex = 0 to oList.Count - 1
				nTotal += len(oList.Item(nIndex))
			next
		ok
	next
	oWatch.Stop()
	return oWatch.Elapsed.TotalMilliseconds

func buildWithPlus nIgnored

	cText = ""
	for nI = 1 to 20000
		cText += "piece " + nI + ";"
	next
	return cText

func buildWithBuilder nIgnored

	oBuilder = new StringBuilder(NULL)
	for nI = 1 to 20000
		oBuilder.Append("piece " + nI + ";")
	next
	return oBuilder.ToString()

func fibSlow n

	nCalls++
	if n < 2
		return n
	ok
	return fibSlow(n-1) + fibSlow(n-2)

func fibCached n

	nCachedCalls++
	if n < 2
		return n
	ok
	for aPair in aCache
		if aPair[1] = n
			return aPair[2]
		ok
	next
	nValue = fibCached(n-1) + fibCached(n-2)
	aCache + [n,nValue]
	return nValue

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. A loop of 200000 additions gives 20000100000 (measured: 1)

2. Same text (20000 pieces), two ways:
   the faster one: Ring's own +=
   same result? yes

3. fib(22): slow = 17711, cached = 17711
   Number of calls without a cache: 114626, with a cache: 44
   the cached version is faster ? yes

4. Reading 500 items: one by one over the bridge vs one call (ToList)
   one call is faster ? yes

How it works#

Stopwatch#

new Stopwatch(), Start(), Stop(), and then ElapsedMilliseconds or Elapsed.TotalMilliseconds. The tutorial prints comparisons ("which is faster?") and not the times, so that the output is the same on every computer; when you try your own code, print the numbers.

Ring's += against StringBuilder#

In C# a StringBuilder is the standard answer to building a long text. In Ring the answer is different: the += of Ring is already efficient, and each Append of a StringBuilder is a call across the bridge. Here the plain Ring version wins. This is the reason for rule 2: advice from another language can be wrong in yours. Use StringBuilder when you need its other features (inserting, replacing, passing it to a .NET method), not for speed.

A cache#

fibSlow(22) computes the same values again and again: 114,626 calls in total for two runs. fibCached remembers each answer (aCache) and needs only 44. The idea is general: if a function always gives the same answer for the same input, remember it. Typical uses: results of a database query, a downloaded file, a converted value, a compiled regular expression.

Note

A cache needs a rule for when to forget. If the data can change, store a time next to the value and recompute after a while, or clear the cache when the data changes.

Fewer calls across the bridge#

Every call to .NET has a small cost. Reading 500 items with oList.Item(i) makes 500 calls; oList.ToList() makes one and gives you a Ring list. When you can ask for a lot at once, do it. The same applies to reading a file (ReadAllLines instead of one line at a time) and to filling a grid.

What you learned#

Exercises#

  1. Measure File.ReadAllLines against StreamReader.ReadLine in a loop on a 10,000-line file.
  2. Add a time limit to fibCached's cache: forget answers older than a minute.
  3. Time new Regex(pattern) created inside a loop and created once before the loop.

Next#

Memory and the garbage collector

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.