代码之家  ›  专栏  ›  技术社区  ›  Tim Reddy

Optimizing memory usage via appropriate data types

  •  1
  • Tim Reddy  · 技术社区  · 14 年前

    所有的,

    我做Java开发已经有10年了……当涉及到管理数字数据时,大部分时间我都坚持了。 int 并使用 double when I need some decimal precision. The reason is we pretty much have a large heap space to work with and exhausting it is pretty difficult for the most part...

    I'm starting iPhone development (I do have some C Programming knowledge) and I'm wondering if I should start looking at using appropriate data types given that the device itself has less resources than your typical JavaEE app...

    例如,我有一个具有一些数值属性的对象(我们将称此属性为“state”)。此属性的值可能只有-10到10。最初,我使用 int 但现在我决定使用 char . 原因是我不需要那么多比特来代表从10到10的值…所以 烧焦 is the smallest I need. Unfortunately, when someone sees a 烧焦 they may think character, but I'm treating it as a number. I'm concerned that I'll probably introduce some confusion if I stick with 烧焦

    So given this code fragment:

    -(void)doSomething:(char)value {
        state = value;
    }
    

    then invoking it such as:

    [myObject doSomething:1];
    

    我的问题是,我是否应该担心以这种方式优化数据类型?我需要开始检查溢出和抛出错误吗?或者这是一个完美的编程?

    谢谢!

    EDIT: I think I shouldn't have used the name state 在我的问题上。当我对这个值执行计算并更新 状态 as appropriate. It just happens to have a fixed range.

    3 回复  |  直到 14 年前
        1
  •  3
  •   Jared Pochtar    14 年前

    While this is perfectly acceptable, (its typically how I do it) unless there are more than one chars in a row, alignment issues will force the next variable to waste 1-3 bytes anyway, which could otherwise have been used for free by an int. I encourage you to investigate alignment, its rather straightforward but a little to verbose to explain + consequences here. At any rate, in order to avoid confusion (although I doubt there will be very much, but basically to each their own) you may want to use int8_t or which is typedef-ed to signed char anyway.

    编辑:我以前忘记了:MacOS上的malloc实现(也是iOS的基础)只返回16字节或更长的内存块,四舍五入。所以如果你是对象,比如15个字节,你也在浪费一个字节,如果它需要17个字节,你就浪费了15个。

        2
  •  1
  •   Johan Kool    14 年前

    In cases like this I usually use a typedef enum containing all valid values:

    typdef enum {
        kMyStateOne,
        kMyStateTwo
    } MyStates;
    

    and write the method like this:

    -(void)doSomething:(MyStates)value {
        state = value;
    }
    

    所以代码的用户知道要使用:

    [myObject doSomething:kStateOne];
    

    这样,如果编译器传递给你其他的东西,你会让他们抱怨。

        3
  •  1
  •   William Jockusch    14 年前

    Unless you are going to be creating an awful lot of copies of this numeric attribute, space is not really an issue, even on the iPhone. 更重要的是学习内存管理和基础数据类型(NSCONTROPE,NSCORE,NSCODE等)。