Skip to content

Instantly share code, notes, and snippets.

@homm
Created June 9, 2012 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save homm/2901168 to your computer and use it in GitHub Desktop.
Save homm/2901168 to your computer and use it in GitHub Desktop.
<?php
$input = '10 20 100 + - 20 * DUP 10 20 + *';
$t = microtime(1);
for ($i = 0; $i < 100000; $i++) {
$stack = array();
foreach (explode(' ', $input) as $chunk) {
switch ($chunk) {
case '+':
$stack[] = array_pop($stack) + array_pop($stack);
break;
case '-':
$stack[] = array_pop($stack) - array_pop($stack);
break;
case '*':
$stack[] = array_pop($stack) * array_pop($stack);
break;
case '=':
$stack[] = array_pop($stack) === array_pop($stack);
break;
case 'DUMP':
var_dump($stack);
break;
case 'DUP':
$stack[] = end($stack);
break;
default:
$stack[] = $chunk;
}
}
}
echo 'Array: ', microtime(1) - $t, "\n";
print_r($stack);
function ap(ArrayObject $arr) {
$last = $arr->count() - 1;
$item = $arr[$last];
$arr->offsetUnset($last);
return $item;
}
$t = microtime(1);
for ($i = 0; $i < 100000; $i++) {
$stack = new SplStack();
foreach (explode(' ', $input) as $chunk) {
switch ($chunk) {
case '+':
$stack[] = $stack->pop() + $stack->pop();
break;
case '-':
$stack[] = $stack->pop() - $stack->pop();
break;
case '*':
$stack[] = $stack->pop() * $stack->pop();
break;
case '=':
$stack[] = $stack->pop() === $stack->pop();
break;
case 'DUMP':
var_dump($stack);
break;
case 'DUP':
$stack[] = $stack->top();
break;
default:
$stack[] = $chunk;
}
}
}
echo 'SplStack: ', microtime(1) - $t, "\n";
print_r($stack);
from __future__ import print_function
import time
input = '10 20 100 + - 20 * DUP 10 20 + *';
operations = {
'+': lambda: stack.append(stack.pop() + stack.pop()),
'-': lambda: stack.append(stack.pop() - stack.pop()),
'*': lambda: stack.append(stack.pop() * stack.pop()),
'=': lambda: stack.append(stack.pop() == stack.pop()),
'DUP': lambda: stack.append(stack[0]),
'DUMP': lambda: print(stack)
}
t = time.time()
for x in xrange(0, 100000):
stack = []
for chunk in input.split(' '):
operations.get(chunk, lambda: stack.append(int(chunk)))()
print('Python list: %f' % (time.time() - t))
print(stack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment