Debug slow code with ticks

October 24, 2011

I made this small snippet of code today, using my style of coding with a singleton class wrapped into a function. The idea is to time the differents parts of the code to find where the code is slowest, and thus, where to improve and optimize. The way you use the code is like this:

tick('Initialize');
/* CODE TO TEST */
tick('Code snippet one');
/* CODE TO TEST */
tick('Code snippet two');
tick()->show();

This will echo something like:

Msg: Initialize
Msg: Code snippet one
Time: 3.543 sec
Msg: Code snippet two
Time: 1.002 sec

Here is the full code:

function tick($msg = ''){
    $instance = ticks::inst();
    if($msg != ''){
        $instance->tick($msg);
    }
    return $instance;
}

class ticks {
    private $tick = array();
    private static $instance;
   
    public static function inst(){
        if(!isset(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }
   
    public function tick($msg=''){
        $time = (string)microtime(true);
        $this->tick[$time] = $msg;
    }
   
    public function show(){
        $last = 0;
        foreach($this->tick as $time => $msg){
            $time = (float)$time;
            echo 'Msg: "'.$msg.'"';
            if($last_time != 0){
                $sec = round($time-$last, 3);
                echo 'Time: "'.$sec.' sec"';
            }
            $last = $time;
        }
    }
}

Is PHP frameworks bound for patterns?

February 12, 2011

I was looking into the code of some common and uncommon PHP frameworks, and all of them proudly showed off their implementation of MVC pattern. Some of them were using a variety of other patterns and techniques – and I was wondering, do they really have to?

I was all confused when the different frameworks had their huge folder structure and a lot of stuff you had to do in order to echo out “Hello World”. And they said it was easy and fast. The fastest and most easy is still to write echo “Hello World”.

Its ok and good to implement MVC structure on a framework – it’s almost a nessecity, because programmers all know what it’s about and can easily adjust. But don’t tell me that your framework is special when it’s not. Dont tell me that it’s simple when it’s not.

I think, on the framework I’m building and the projects I’m working on, that the framework frees me from being bound to MVC and patterns (or was it the other way around, that they bind me to use MVC and patterns?). Instead I create my own based on the needs of the site (it be an abstraction of MVC or other patterns). Frameworks, in my opinion, is for abstracting away some code and make it easy to write the application. I like thinking new and creative.

But the again. I never liked frameworks. So my vision is clouded in the matter, I admit that.


Sexy Code

February 5, 2011

Why does JavaScript get all this attention and rethinking these days? Wherever I turn my browser there is a lot about jQuery, node.js, prototype etc. Why cannot the same techniques be applied server-side, on PHP? Aint PHP sexy? JavaScript was not sexy at a point until someone made something with it and it became fantastic and easy. How did that happen? Are JavaScript developers more creative? Is it a better and more flexible language? Is it because its front end and handles interaction?

Well. I’m going to try to code sexy when I do PHP. Right now I’m writing this html parser that is neat and cool. I want to be a part of server-side language revolution with PHP. It has potential! I don’t want to hear about Ruby on Rails, .Net or Python – lets empower PHP, and get rid of all that crappy code out there.

I’ve programmed a database class multiple times, and its an evolution. This happens in every aspect of my code all the time, and that’s really a journey. Here are the database example:

First it was spaghetti.
Second time I made it in a config file.
Third time I switched out mysql with mysqli and made some functions.
Fourth time I made the database a class.
Fifth time I accessed it through a controller and DAO classes.
Sixth time around I made it a singleton and reused the connection.
Seventh time I added pconnect and it became persistent.
Eight time, then the database object extended the mysqli class.
Ninth improvement was to make a ORM expand the connection.
Tenth evolution was to make an easier access for the creation of advanced queries.
Eleventh time, I made the ORM chainable and combined more advanced queries to it.
Twelfth thing was to improve the to interact with different kinds of result sets.
Thirteenth, in the end, the chainable database singleton class extending mysqli got wrapped in a function for easy access.

How do you like this kind of code:
echo query('tablename')->columns('id, name, regdate')->where('id > 155')->orderby('name')->asc()->toarray()->html();

And the future still brings more:
– The code to support multiple different databases
– Extends the support for joins and relations
– Add better template engine to the output presentation
– Make the mess faster

That is what I’m currently working with…


Database connection speed in php

September 2, 2010

So, on this current project of mine, I have one unfinished page that have currently 31 fast mysql queries(to a database that contain a very little data) – and I wanted to see how different settings would affect the speed. I have heard that connections are costly, but how costly are they really? These are the average results of my little test:

One connection for each query: 0,045 sec
One persistent connection for each query: 0,025 sec
One connection used in a Singleton pattern: 0,0175 sec
One persistent connection used in a Singleton pattern: 0,0165 sec

Summary:
The old method is the slowest by far! If you have many concurrent users on the webpage persistent connection will help a bit. But the best effect is from using a Singleton connection – or another method where you use one instance of the connection on all the queries. Persistent connection uses some time fetching the connection from mysql on the server, so it’s faster to do it in code.


Storing Images with PHP & Mysql – The right way

April 22, 2010

I’ve in that stage of my latest project that I have to decide how to store images to the server, and how to use the database the best way to do this. I know that I’ve done this wrong a couple of times, but hopefully I’ve find a good practice of this now. Not quite sure if this is the best way, but this is how I think after looking into the matter:

There are several things I consider to be important:
1. SEO.
The filenames need to be descriptive and searchable.
2. Database
Images should not be stored in the database, but the filename and id should. You need to know what image goes with what movie. It is possible to store images into database, but it makes the database big and I can image working with the images becomes little more complicated. There are advantages to this too, but it is not the way I’m going to do it.
3. Thumbnails
It’s a good practice not to resize in the <img> tag, so a good system for thumbnails must be at hand.
4. URI
Where to put the files is also something you have to consider carefully. Is it best to put everything in one folder? Probably not. What about “movie-id/images/image.jpg” or “images/movie-id/image.jpg”? Much better.

Let’s take an example database with four tables: Movie, ImageType, MovieImage and Image

Movie:
Important part of movie is that it must have an id and a title.
ImageType:
Must have an id and a type, ex: cover, poster and screenshot
MovieImage:
Realtionship between the movie, image and type. Contains the foreign key to image, movie and imagetype, where one of them has to be unique.
Image:
The image should have an id to the image so that it can be connected to a movie and made unique. In addition it should contain a filename, that is generated in php from the id, title of movie and type of image.

Cooking it all together:
The filename must be SEO optimized, so the syntax to use should be like: id-type-movie-name.jpg. You could remove the type from the name, but it’s a good way to distinguish between the different image types, making the SEO better too. Movie name should be separated by a hyphen to be most SEO friendly. By storing filename once with id instead of generating it every time and out from id, type and title is good practice because if the title is changed (from “Lord of the rings” to the more accurate “The Lord of the Rings: Fellowship of the Ring”) the filename points to the right file – id-type-lord-of-the-rings.jpg. Generating thumbs could then follow a standard of adding a -thumb-width-height or something to the name – or simply create it on the fly with a php method, even thou I think the first option is more correct. When getting all images to a movie you can easily sort by type, and get the filename from database – and then show it on your webpage by creating the correct url, ex: images/movie-id/1923-cover-lord-of-the-rings.jpg.

By thinking like this, the image uploading and storing become much more simplified for me than how I’ve done it before.


Learn Best Practice, don’t settle for them

March 11, 2010

I’m always trying to find what they call “Best Practice” on the problems that occur when creating a website, but they are not always easy to find on the specific problems, and sometimes they are a little bit hard to understand. For example, a lot of Best Practices are described in so-called Patterns, a template of how to build your website, but these Patterns is often hard to understand – especially if you’re trying to force them into your code. When you code a bit, and you get into a problem that one of these patterns append to, then you often understand why this is called a best practise and learn it. When you have learnt it, you can then use it and modify it to match your project in a better way.

I recently read the article Your Website is Unique. Don’t Settle for Best Practices. at Future Now, giving a little more insight at why not always settle for the best practice(when you want to increase conversion rate). The main idea is that your web page is unique, and that you have to use whatever changes that makes it unique instead of going for solutions that are made of someone else. I’m taking this idea further, to the stage when you are coding your site, instead of optimizing it.

Dont get me wrong. I still love best practices. I still are going to look for those problem solving patterns. They might be much more important in the back-end than in the front end. The thing I’m going to make sure to take into consideration is, if these best practises are best for my unique site, and that they don’t make my ideas become a copy of someone elses. Code as you can, so that you understand your code and are able to modify it with ease.

Test your code, and consider other programmers solutions after you fully understand them.

As an example, I can take the first guest book that I “programmed”. I didn’t know PHP very well back then, and had never used MySQL to store anything – so this was really basic. For me it looked like code I did not understand, so I copy pasted it, modified a bit, and got it to work – but I did not really understand it. So, when I now look back at that code, I se how flawed it was, because now I know how to code it. Even thou that guest book code was made by a programmer, based on some good practices at that time, I did not learn or know about them back then. When I look back at it now, and understand the logic, I see that even the original script was flawed, because it do not match the criteria I’ve now learned to be good code.

So, are you an experienced programmer, your code are probably mostly very good practise. Are you an average programmer, you’ll probably learn a lot from these experienced programmers. But if you are a unexperienced programmer, learn first the basics, understand the code of average programmers, and strive to achieve understanding of good code. This way, you can make your site your own. I consider myself average, that is trying to achieve what experienced programmers can do.


Persistent MySQL connection

February 23, 2010

It was not that long ago I figured out what this ment, even thou persistent is kind of self-explanatory. I read that this was a must on a sql connection, but I never learnt it at school or did find out how to do it. For me it was a fancy word for a more complex connection type, but is it really more complex?

What I usually do, is that I use the singleton pattern on my database connection so that on each load the connection is created only once and then reused for every new use. A database connection is expensive, so it is a good thing not to create it a lot, and this is what singleton does. A persistent connection is like a singleton to the server – and does the thing that I hoped singleton would do when I first heard about it.

A persistent connection does not close, but it reused by the different connections to the server. This means that the same connection is reused by every user that connects to the server, and there is not created a new one for each time. Sounds simple? It is simple.

The real use of it is probably only when you have a bigger site with many users and traffic is big, so it is not really necessary for small websites that barely use a connections and have under 50 visitors a day. The singleton helps a lot on each user page load, when the connection is preserved and reuses for the page load, but still, using a persistent connection could slightly improve speed even thou it is probably not noticeably. The real problem solved with persistence is that you can have many more simultaneous connections to the database – getting rid of the connection overhead problem.

How to do it?
I use the mysqli extension for PHP, and the only thing needed is to add a ‘p:’ to the host address, like this:

$db = new mysqli('p:localhost', 'username', 'password', 'databasename');

This only works with PHP 5.3.0 or higher, so be sure you have it both locally and on the server. I you don’t have it or don’t use mysqli, then there is an alternative, to switch form mysql_connect to mysql_pconnect.

That simple, really – and no other change to code.