Toby Smith

Posts for the ‘Technology’ Category

Javascript Performance

20th March 2013

I’ve become quite enamored with using jsperf to benchmark the efficiency of code.

Two of the more interesting ones I’ve done (so far) are:

A comparison of various array concatination (appending one to the end of another) techniques

I look at: arr.concat, arr.push.apply(a,b), jquery’s merge and a couple of looped approaches.
The winner by a landslide:

while (b.length) {
  a.push(b.pop());
}

Even if you have to go through a few layers to access it (on the Chrome and Firefox versions I tested). Awesome!

The other was more frustrating.
A top-n sorting algorithm
Say for instance you want the top-n from an array. You’d think it might be more efficient to not have to sort the whole array and just maintaining the top few.
You’d like to think that wouldn’t you.

If you’re not using Google’s V8 engine, then you are! They seem to have uber-charged their sorting. Which is awesome. If somewhat irritating given the time wasted on custom sorting methods. 🙁
I tested it with some custom Insertion Sort and Binary Sort methods. I’m not sure a divide and conquer approach would be relevant here, but it might be worth a look.
Also worth considering the size of your n compared with the size of your arrays. I wonder if things got a bit more hairy (n = 5 ; array.length = 10,000,000) whether things would change.

Cylinder between two points (OpenGL C++)

4th December 2010

Whilst working on one of my projects this year for uni I was looking for some code to draw a cylinder between two points (using OpenGL). There were a couple of solutions out there, but they weren’t that great.

I couldn’t find one that worked reliably and simply (without lots of different if statements trying to catch different cases). Anyway, after a bit of thought I knocked this one out. It’s actually a lot simpler than you think…which is probably why people haven’t bothered to post it.

Anyway…enjoy some pseudo code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Vector3D a, b; (the two points you want to draw between)
 
// This is the default direction for the cylinders to face in OpenGL
Vector3D z = Vector3D(0,0,1);         
// Get diff between two points you want cylinder along
Vector3D p = (a - b);                               
// Get CROSS product (the axis of rotation)
Vector3D t = CROSS_PRODUCT (z , p); 
 
// Get angle. LENGTH is magnitude of the vector
double angle = 180 / PI * acos ((DOT_PRODUCT(z, p) / p.LENGTH());
 
glTranslated(b.x,b.y,b.z);
glRotated(angle,t.x,t.y,t.z);
 
gluQuadricOrientation(YourQuadric,GLU_OUTSIDE);
gluCylinder(YourQuadric, RADIUS, RADIUS, p.LENGTH(), SEGS1, SEGS2);

Hope that helps someone out there.

http://www.thjsmith.com/feed">RSS Feed
  • Terms of use
  • Privacy Policy