improve memory efficiency about 20 percent, add tests