作弊PHP整数 [英] Cheating PHP integers

查看:72
本文介绍了作弊PHP整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与我在这里的帖子有关,但方向却截然不同 PHP中的字符集检测

This is in relation to my post here but taken in a completely different direction Charset detection in PHP

本质上,我希望减少许多巨大数组导致的内存.

essentially, i'm looking to reduce the memory that many huge arrays cause.

这些数组充满了整数,但是看到PHP内部使用32位和64位整数(取决于您为CPU类型编译的版本)后,它将占用内存.

These arrays are just full of integers but seeing as PHP uses 32bit and 64 bit integers internally (depending which version you have compiled for your CPU type), it eats the memory.

有没有办法欺骗PHP使用8位或16位整数?

is there a way to cheat PHP into using 8bit or 16bit integers?

我已经考虑过使用pack();为此,我可以拥有一个打包的二进制值数组,并根据需要解压缩它们(是的,我知道这样做会使它变慢,但比加载然后在每个数组中逐个运行每个流的方法要快得多.文本通过,因此它们都必须同时存储在内存中以保持速度)

I've thought about using pack(); to accomplish this so I can have an array of packed binary values and just unpack them as I need them (yes I know this would make it slower but is much faster than the alternative of loading and then running through each array individually as you can stream the text through so they all need to be in memory at the same time to keep speed up)

您能建议任何更好的替代方法来完成此操作吗?我知道这很hacky,但是我需要防止大量内存激增.

can you suggest any better alternatives to accomplish this? i know it's very hacky but I need to prevent huge memory surges.

推荐答案

不要告诉任何人!

class IntegerstringArray IMPLEMENTS ArrayAccess {

    var $evil = "0000111122220000ffff";

                 // 16 bit each


    function offsetExists ( $offset ) {
        return (strlen($this->evil) / 4) - 1 >= $offset;
    }

    function offsetGet ( $offset ) {
        return hexdec(substr($this->evil, $offset * 4, 4));
    }

    function offsetSet ( $offset , $value ) {

        $hex = dechex($value);
        if ($fill = 4 - strlen($hex)) {
            $hex = str_repeat("0",  $fill) . $hex;
        }

        for ($i=0; $i<4; $i++) {
            $this->evil[$offset*4+$i] = $hex[$i];
        }
    }

    function offsetUnset ( $offset ) {
        assert(false);
    }

}

因此,您几乎可以从中创建一个数组对象:

So you can pretty much create an array object from this:

$array = new IntegerstringArray();
$array[2] = 65535;
print $array[2];

它在内部存储列表并接受16位整数.数组偏移量必须是连续的.

It internally stores a list and accepts 16-bit integers. The array offsets must be consecutive.

未经测试.只是作为实施指南.

Not tested. Just as an implementation guide.

这篇关于作弊PHP整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆