# Efficiency

As a general question, what ways are there to make a program more efficient and faster?

@Coder You’re asking us to put a whole book into a few lines of information. No matter what someone does, there is probably somebody else who can make it better, faster, and smaller. A lot of that comes from experience and how well you know the particular language you’re using.

EDIT: I’ve been using Codea (lua) for almost 2 years and there’s still a lot of the language that I’m not that familiar with. It takes a long time and a lot of coding to learn everything.

@dave1707 thanks. I will try and read up on it.

@Coder You’ll probably get more responses on you question. I just feel it’s a really broad question.

try to google the question. There are some answers on the web and into this forum too.

I agree with @dave1707 that you could write a book about this, but at the same time I feel someone new could use quick tips on things that may seem obvious to the experienced coder. Those can be easily put into bullet points. Here is my first bullet, I invite all of you to add more to the list!

1. If you are doing math, local variables are WAY FASTER! Always use:
``````local x = ...
``````

``````x = ...
``````

You can do the same with the math functions and constants:

``````local pi = math.pi
local atan2 = math.atan2
local sqrt = math.sqrt
local x, y, length, theta
for i = 1,N do
x = someTable[i].x
y = someTable[i].y
length = sqrt(x*x+y*y)
end
``````

There are a ton of resources out there to help you with speeding up Lua’s performance but no so much Codea’s. Unfortunately these next few examples are Lua tips i picked up along the way and only two of them specifically applies to Codea.

####1.1 Styling functions

``````function setup()
ages = {24, 26, 1000}
end

function draw()
background(123, 213, 31)
fill(255, 255, 0)
fontSize(20)
for identifier, value in ipairs(ages) do
text(identifier .. ": " .. value, WIDTH/(#ages + 1) * identifier, HEIGHT/2)
end
end
``````

Take all your styling functions `background, fill, stroke, font` out of the for loop for a small speed bump

####1.2 Fake Lines

``````function setup()
ages = {24, 26, 1000}
end

function draw()
background(123, 213, 31)
fill(255, 255, 0)
fontSize(20)
for i=1, #ages do
text(i .. ": " .. ages[i], WIDTH/(#ages + 1) * i, HEIGHT/2)
end
rectMode(CENTER)
rect(WIDTH/2, HEIGHT/2-80, 140 * (#ages), 5)
end

function touched(t)
tablePos = #ages
tablePos = tablePos + 1
ages[tablePos] = math.random(20, 30)
end
``````

Use `rect` instead of `line()`, because, er, it’s easier, i s’ pose
I actually have no idea where i picked this one up from or whether it has a basis at all, but i’m pretty sure i got it from the forums so it must be right, right?

####1.3 Iteration

``````function setup()
ages = {24, 26, 1000}
end

function draw()
background(123, 213, 31)
fill(255, 255, 0)
fontSize(20)
for i=1, #ages do
text(i .. ": " .. ages[i], WIDTH/(#ages + 1) * i, HEIGHT/2)
end
end
``````

Don’t use paris, and especially ipairs, by avoiding them and using the `#` length operator you can double the speed of your code

####1.4 Append

``````function setup()
ages = {24, 26, 1000}
end

function draw()
background(123, 213, 31)
fill(255, 255, 0)
fontSize(20)
for i=1, #ages do
text(i .. ": " .. ages[i], WIDTH/(#ages + 1) * i, HEIGHT/2)
end
end

function touched(t)
tablePos = #ages
tablePos = tablePos + 1
ages[tablePos] = math.random(20, 30)
end
``````

Try and avoid using `table.insert`, if you must, localize the insert function `insert = table.insert`. When possible use `table[#table + 1] = "newValue"` or keep track of the table size (as shown in the example).

And above all localize everything you can, every chance you get, when appropriate,

A lot of people will tell you that the first rule of optimization is not to do it, this is partially true. After running some break tests on your program, as long as they handle them fine, there’s no need to speed things up, however if you have time and it’s not just some one off project you’re working on, optimize away

Thats all for now, i’ll be back later for more once i finish what i was meant to be working on

@Jmv38 and @MoNus thanks for the replies and I agree that I probably should have googled this question first.

@Dalorbi thanks for the advice. yes I agree, optimisation for optimisation’s sake is pointless but one of my programmes started running at 10fps because of some simple issue.

@Coder - the biggest speed problem with Codea is usually the graphics. There are too many things to list here, but read up on setContext (or do a forum search for examples) as a way of pre-drawing frequently used images.

A general question of “how do I speed up my code” is very broad and unspecific. If you want a good and specific answer, we’d need to have the code or know what functions you use a lot.

@Ignatz thanks I have heard of set context but don’t fully understand it yet. @SkyTheCoder sorry I should try to understand what I’m asking you guys before I post next time.

@Coder If you’re looking for a great example of setContext(), @Ignatz has one here

Explanation time:
Assuming you followed the previous link, copy the code into a new Codea Project and lets get analysing.

####Line 2: `grid=image(750,750)`
This is the first important line. It tells Codea to create a blank 750 by 750 pixel image called grid

####Line 3: `setContext(grid)`
This line tells Codea that instead of drawing (ellipses, text, rect, meshes, sprites) to the default output (the screen), draw it onto the image

####Lines: 5-9

``````    for i=1,750,25 do
for j=1,750,25 do
ellipse(i,j,4)
end
end
``````

These lines simply and effectively draw a grid of different circles (meant to look like points on a grid) onto the image
5: Starts a for loop,Tells Codea that a variable labelled i should increment by 25 until it reaches 750
6: Starts a (nested) for loop, Tells Codea that a variable labelled j should increment by 25 until it reaches 750 (this loop will be run for each of loop `i`’s 30 iterations)
7: Draw an ellipse at the specified location (Which is different everytime because it’s using the values of two ever-changing for loops). Note: circle color will be white as defined by line 4’s `fill(255,255,255,70)`

####Line 10: `setContext()`
Tells Codea to reset the draw focus (or context of drawing) to the screen again

####Line 16: `pushMatrix()`
Tells codea to save current `scale() transform() rotate()` values and “Pushes” them to the top of a stack. Usually used to scale, transform and rotate certain objects without affecting the entire program.

####Line 17: `scale(Zoom)`
Increases how much the camera is “Zoomed” in or scaled by, based on the position of the sliding number parameter defined in line 11’s `parameter.number("Zoom",.1,5,1)`

####Line 18: `sprite(grid,WIDTH/2,HEIGHT/2)`
Remember how we drew a whole bunch of circles or “dots” onto the image grid? Well you should, because its now being drawn onto the screen as a sprite. You may be thinking “Why all this trouble to draw some dots”. The answer is: To prevent Codea from having to do those for loop calculations 60 times a second.

####Line 21: `popMatrix()`
This line just returns `scale() transform() rotate()` to their previous values i.e. `1, 0, 0`
Even though the return to their normal states, our previous drawing operations are unnafected because they happen between the `pushMatrix` and `popMatrix()` calls. In case you’re wondering, yes, `pushStyle()` and `popStyle()` do the same thing except focus on preserving and reapplying `fill(), stroke(), tint(), *Mode() --Where * is lineCap, ellipse, rect or sprite` And all the text property settings functions

Note: Please don’t feel patronized by me if i seem to be spoon feeding you. I’m just describing this how i wish the non-programmer me would understand, and for all the lurkers out there, too afraid to come out into the light (Trust me, it doesn’t hurt)

@Dalorbi thanks i finally got that working, that must have been why my program was so slow.