Archive for the ‘Programming’ Category

10 PHP Optimisation Techniques

Sunday, January 20th, 2008

Many people write php code without knowing how to optimise it properly to make it run faster. By applying some simple coding techniques your php script can run faster and save cpu workload. Also if your script is large then pages will load faster if the script is optimised.

1. Arrays are slower than normal variables. The speed difference is significant. Obviously only applicable to when you use small arrays. I calculated the array to take about twice as long.

2. Arrays are faster than objects. This is again a significant speed difference. Decide whether is is worth having objects in all cases. Consider using an array instead. The objects took about twice as long.

3. Functions outside of objects are slower than functions inside of objects. The function within the object takes roughly 50% longer.

4. Local variable inside a function are fractionally faster than global variables. Consider setting local variables to the value of the global variable if it is going to be used in a loop. The global took roughly 15% longer.

5. Multiplication is slightly faster than division. So it is better to multiply by 0.5 than divide by two. Consider pre calculating a division outside of a loop by storing 1/value and then multiplying with the new value. the division took about 10% longer.

6. Multiplication is a lot faster than the pow() function. Use $x * $x rather than pow($x, 2). the pow() function took roughly four times as long.

7. Receiving the return value from a function is slower than if you do not receive it. When your script is complete then the error checking by looking at the return from a function may not be necessary. Setting the variable took roughly 18% longer.

8. Using a loop is faster than using a recursive function. See if it is possible to code with a loop.

9. echo() is faster than print(). This is due to generally unnecessary error checking in print().

10. Single quotes are faster than double quotes. This is because with double quotes the text inside the quotes is checked for variables and other things. There are times to use each one but I will not go into it in depth here. Basically use single quotes when the text is completely static.

11. (Contributed by InSp3KtaH) You should not change the type of a variable. It you set $foo = 1 then you should keep it as a number. It takes time and memory to change the type.

You may have noticed that some of these techniques could come into conflict with keeping well written object orientated code. In each case you have to consider the pros and cons. There are no fixed rules so you will have to decide whether to sacrifice feed for code clarity. If large loops are to be found in your code look at optimising these very carefully as that is where a lot of performance goes.

Javascript Physics Engine 3

Sunday, January 13th, 2008

Here is another update on the physics engine. This time it is all about circles colliding with other circles. Still perfectly elastic collisions. The collision mechanism can now cope with an overlap so stuff doesn’t stick together.

Also collisions with different mass objects have been implemented so now big circles are heavier and the effects on the collisions are apparent. This version is more interesting to watch since the balls bounce off at lots of different angles depending how they hit each other.

Rectangle collision has been removed because it was only a small experimental measure. It will go under the polygon collision category since rectangles are polygons. The object creation back end has been modified to add the polygon object. Creating a rectangle now does in fact create a polygon in the background although you cannot see this.

http://www.quantumstate.co.uk/physics/physics3/

Javascript Physics Engine 2

Saturday, December 1st, 2007

I have now made an update to my physics engine. I have put in some basic collision detection which is rectangles only so far so there will be no circles in sight this time. The balls change colour when they collide, I put this in for debugging and I thought it looked pretty so i haven’t bother to remove it from the display.js file.

Also there are different size square now (rectangles also work but I prefer squares). Also they actually bounce off the right hand wall rather than bouncing off something just past the right hand wall. In my example there is no check to see if the squares overlap at the start and the collision detection can’t handle the big overlap so if you get this refresh the page and hope you don’t get an overlap.

At the moment the collision detection is fairly crude because it just handles rectangle to rectangle. I have planned out a few algorithms for circle-circle collision and more advance square-square collision which should work with rotated square.

If you come across any bugs please tell me. I have found some bugs that have been quite rare when I was testing before (one happened when the squares collided so that the corners hit each other) so I may bot have picked some of them up.

http://www.quantumstate.co.uk/physics/physics2/

Javascript Physics Engine

Monday, November 19th, 2007

This is my latest javascript project, using the canvas object. I have posted about making a 2D and 3D lindenmayer system earlier on. I don’t really like the flash platform mainly because you have to pay for flash and I also don’t really like the way the movie clips are handled in the script from when I have used it as my school. This means that javascript is the only other option really for anything web based (Microsoft silverlight isn’t popular enough currently).

I found that some people have used native features of internet explorer to create a canvas object that works in internet explorer. Unfortunately this is terribly slow currently but there is nothing which can be done about that. This means that my example script does with with internet explorer and amazingly no modifications were needed other than including the explorer canvas script.

At the moment my physics engine is woefully incomplete. At the moment there is no collision detection other than with the floor and both walls. I am going to be working on the collision detection next since it is a pretty major part. I am still playing around with different algorithms currently, looking for a high speed routine. The system for adding dynamic and static objects to the world works well enough for now but I will expand this as features are needed. I haven’t put any static features in the demo because they are not very exciting since they just stay there and don’t even collide with things. Gravity is implemented.

I have only put in a small number of objects because I felt sorry for the people with internet explorer. Hopefully the final release will be feasible for IE because there shouldn’t be too many dynamic objects to be drawn and I should be able to get a pre-rendered scene for the static objects. The rest is done in plain javascript which doesn’t take a big performance hit.

First physics engine example.

Mandelbrot Set

Saturday, November 17th, 2007

The Mandelbrot set is an interesting mathematical concept because it is so amazingly simple yet it leads to such astonishingly complex results. I thought it would be interesting to have a go at making my own Mandelbrot set generator. I chose php because I was also interested in looking at optimisation techniques and a Mandelbrot set generator definitely needs all of the optimisations it can get.

Having made the program I have now realised that php is just not cut out for doing stuff like this so it would be a better idea to make it in something like c++ so that I could add more features like being able to smoothly zoom into the picture perhaps, or at least cut down the 25 second rendering time for a 500×500 picture.

First, since the Mandelbrot set uses complex numbers, I logically looked towards procuring a complex number class for php. I found a class pretty quickly but fortunately (yes it isn’t a typo) it wasn’t documented. This meant that I didn’t feel the urge to thoroughly scan the code to work out how to use the thing so I gave up on it saving myself time and bother. Later on in the script when I was optimising I realised that classes are a lot slower than normal variables, I think it would have been over 4 times slower at the lower estimate.

For those of you who don’t know the formula for the Mandelbrot set is z -> z^2 + c. Where z is a complex number which starts as 0 + 0i and c is the point of the complex plane that you are looking at. The formula is repeated large numbers of times and in my program I allowed this value to be changed. If z goes off to infinity (as soon as |z| > 2 you know it will just keep increasing) then the point is coloured white otherwise it is coloured black.

You will now look at my program or many other Mandelbrot set pictures and point out that they are all in pretty colours. The reason for this is that we programmers like pretty pictures, since the Mandelbrot set programs don’t produce anything else, so we look at how many iterations it takes until |z| > 2 and then work out a colour based on this value. My program works in the range from bright yellow to red since I was too lazy to program in a whole spectrum gradient but many other programs will use the full spectrum or something even more exotic.

There isn’t really much more to it than that and the program is pretty short. My PC takes about 25 seconds to render the 500×500 with 100 iterations and I have a p4 3.2 Ghz so everybody should be able to have a go at rendering it if they want to and they have php installed. I haven’t put the php script on my website because I want to keep on good terms with my host and I don’t think locking up the cpu for about 20 seconds will please them.

To use the script put it on your server (preferably on your own PC) and then open the web page. If you want to change the things you are looking at just adjust the constants and variables at the top of the script. They are pretty self explanatory. The iteration number will probably need to be increased if you decide to zoom in but when you aren’t zoomed in it should be kept low to speed things up.

The Code

An image generated my my mandelbrot set.

Installing Eclipse on Windows

Wednesday, November 14th, 2007

I am writing this post because when I had a go at installing the eclipse development platform I had a bit of trouble getting it installed and working. I would imagine that most people wouldn’t encounter this problem but I had real trouble finding any information on it so I thought I would post the fix.

To install eclipse you first download the zip from their website and extract it to wherever you want the program to be stored. There is no installer so you will want to create shortcuts etc. yourself. This can be easily done by right clicking and selecting the new shortcut option.

When I had unzipped I tried running the Eclipse.exe file however it produced an error saying

“A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available to run Eclipse. No Java virtual machine was found after searching the following locations:
location_of_script\jre\bin\javaw.exe”

This was surprising because I have a working installation of Sun Java that has been picked up by every other Java program that I have ever tried to run. Searching the internet didn’t turn up any obvious fixes however after a bit of searching I found out that there is a command line parameter that you can set to specify the location of your JRE.

So to fix this error you must first find you JRE. Mine was fairly easy to find, just by browsing the program files folder and looking in the Java folder and then the bin folder within that. If you have trouble then just run a search for “java.exe” and it should find it. Write down or copy the path of the java.exe file making sure oyu include \java.exe.

Now go back to the location of your eclipse installation and create a new shortcut to eclipse.exe (right click -> create shortcut). Now right click your shortcut and go to properties. In the target box go right ot the end of the string and then type:

-vm “MyJavaPath”

Where MyJavaPath is the path to your java.exe. So for example target ended up looking like this:

“C:\Documents and Settings\MyUsername\Desktop\eclipse-java- europa-fall2-win32\eclipse\eclipse.exe” -vm “C:\Program Files\ Java\jdk1.5.0_07\bin\java.exe”

Now you should be able to launch eclipse by running this shortcut. I have yet to find a way to get eclipse to remember where your java.exe is so you will have to use the shortcut to launch it for now.

I hope this helps some people who are having problems.

Google Android

Wednesday, November 14th, 2007

Google Android is a new mobile phone software development kit that has been created by the Open Handset Alliance and is prominently supported by Google. The SDK has just been released for developers and it uses the Java programming language. The applications are compiled before being loaded onto the device. There is a virtual machine provided with the SDK to allow for testing the software.

There have been mixed reactions to the announcement from various people. Notably a spokesperson from Symbian, a company whose platform powers millions of mobile phones, said “It’s very clear what developers want - volume and a stable platform that doesn’t keep breaking. You have to have a lot of zeroes in your sales figures before a developer gets out of bed.” This may indeed be what the professional developers employed by many large companies want however Google looks to be targeting a different sort of developer.

Google has launched the Android Developer Challenge which has $10 million worth of prize money for applications for Android. This is clearly meant to entice large numbers of developers to take part and I would think that many of them will be interested in the open source movement. You could argue that most of the applications submitted will be of a fairly poor quality, produced by amateurs who don’t really know how to design and polish an application, there will undoubtedly be a lot of these kind of applications. However I would imagine that there will also be a large number of high quality applications produced, partly just because the scope for developing for a mobile device is far more limited compared to a PC.

The screen area is very small as well as the processing power so large complex menus and interfaces just aren’t possible, the simplicity of the applications works in the favour of small scale developers. Also I have looked at the developers kit and there is a good framework and API set there to work with. The system encourages use of mashups as they are called where the developer takes several existing elements and combines them in a unique and useful way.

If you are a developer I would recommend taking a look at the SDK since it is fairly interesting and if you are anything like me new cool things are exciting. Even if you are not a developer you might be interested in just looking at the platform in the emulator although I guess it is quite a lot of bother with all of the downloading.

http://code.google.com/android/

3D Lindenmayer Systems with Javascript

Friday, November 2nd, 2007

Just cloning the Lindenmayer script which I found seemed a bit simple and a bit like I was copying them. So I decided that I would use my knowledge of 3D programming which I picked up in VB (you can see the tutorials on the main site) and make a 3D version of the Lindenmayer System. The 3D code is basically a direct port from my 3D VB code which used matrices to perform the transformations.

I have put this script on a separate page because to rotate and move the object so you can get a better look the keyboard is used so people scrolling with the arrow keys or trying to type a comment could encounter problems.

Here is the link 3D Lindenmayer system.

See my previous post for more Lindenmayer system stuff.

HTML Canvases and Lindenmayer Systems

Tuesday, October 30th, 2007

I recently noticed that there is a canvas feature that has been implemented in most modern browsers (unsurprisingly not IE7). The canvas allows you to draw things using javascript which is a really nice feature. It opens up several possibilities for interactive applications in a way that runs reasonably quickly and doesn’t involve many pictures. I came across a website that had used the canvas for what is called a lindenmayer system. I have just take the idea from this website and I coded a version myself. If you look at the code we have implemented it fairly differently although the systems are obviously pretty similar.

It was quite fun to make, I had done a project that parsed a small expression in VB a couple of times so I knew how to implements that and the rest was just using the functions of the canvas system to rotate and draw lines. I have put my implementation below, you can give it a formula, tell it how many iterations to do and there is also a scaling option. The script has a go at scaling but it isn’t very good, all it does is scale it inversely proportional to the number of iterations so 2 iterations is half size, 4 iterations is a quarter etc. This will not work in Internet Explorer.

Lindenmayer system

Please post any interesting formulas that you find. The script has no error checking so I would avoid putting in stupidly big iterations since it will never complete and might lock up your browser.

Cross Browser Scripting

Saturday, October 20th, 2007

Recently I have written an ajax tutorial. It was interesting and fairly easy to make since I was mainly using some normal ajax which I had lying around. The main point of the tutorial was to show that it would make a practical website.

The main code for the tutorial was written in a fairly short period of time, then I tried testing the script in Internet Explorer, which I probably should have done earlier. Suffice to say, the script did not function properly in Internet Explorer.

The strange thing about this bug however was that, although it did the same every time the page was loaded, what it did didn’t really make sense. It would run the first ajax request and then would not run any more requests. So my ajax code was correct because it worked but it only ran once. There was no errors according to IE’s debugging stuff. I still do not know why this error happens however I managed to find a solution on the internet. It involved switching round two lines of code.

http.onreadystatechange = handleResponse;
http.open('get', webpage);

Had to be changed to:

http.open('get', webpage);
http.onreadystatechange = handleResponse;

But this should not have been needed. Why should opening a connection change what function was attached to the onreadystatechange event? It doesn’t matter in other browsers, nor the first time the script is run.

The annoying thing was that I spent about 30 minutes trying to fix this, which was a disproportionate time to writing the script. First I thought it was due to the way that I called the function so I spent a while messing around with different ways of doing this, none of which fixed it. I know debugging code takes a while but I don’t see why it should take so long to make it work in another browser which should be implementing javascript in the same way.

There is also a problem when using css and html, and most often your code works properly in everything other than Internet Explorer. Most web developers will tell you this if they have tried developing for multiple browsers with slightly complex things. This is the main reason why I am so pleased with the growing popularity of non IE browsers. Hopefully this will encourage the internet explorer developers to increase compatibility with the W3C’s standards because it is greatly irritating for a web developer.