在java中编写单例的经典之处如下:
public class SingletonObject
{
private SingletonObject()
{
}
public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}
private static SingletonObject ref;
}
Run Code Online (Sandbox Code Playgroud)
如果我们需要在多线程情况下运行,我们可以添加synchronized关键字.
但我更喜欢把它写成:
public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
public static SingletonObject getSingletonObject()
{
return ref;
}
private static SingletonObject ref = new SingletonObject();
}
Run Code Online (Sandbox Code Playgroud)
我认为这更简洁,但奇怪的是我没有看到以这种方式编写的任何示例代码,如果我以这种方式编写代码会有什么不良影响吗?
我写了一个简单的斐波纳契测试程序来比较node.js和python的性能.事实证明python花了5s来完成计算,而node.js以200ms结束为什么python在这种情况下表现如此差?
蟒蛇
import time
beg = time.clock()
def fib(n):
if n <=2:
return 1
return fib(n-2) + fib(n-1)
var = fib(35)
end = time.clock()
print var
print end - beg
Run Code Online (Sandbox Code Playgroud)
的node.js
var beg = new Date().getTime();
function fib(n)
{
if (n <= 2)
return 1;
return fib(n-2) + fib(n-1);
}
var f = fib(35);
var end = new Date().getTime();
console.log(f);
console.log(end - beg);
Run Code Online (Sandbox Code Playgroud)