Changing internal representation in runtime

烈酒焚心 提交于 2019-12-03 21:26:42

If you have a type where 99% of the values could be represented in one fast, powerfull type, and only 1% in a very heavy type, (say int vs. BigInteger) How to represent it??

BigInteger implementations typically do exactly that; they keep everything in ints or longs until something overflows, and only then do they go to the heavierweight implementation.

There's any number of ways to represent it. A pattern I like is:

public abstract class Thing
{
    private class LightThing : Thing
    { ... }
    private class HeavyThing : Thing 
    { ... }
    public static Thing MakeThing(whatever) 
    { /* make a heavy or light thing, depending */ }
    ... etc ...
}

Are there guidelines for mixed representations, when to use them, when not?

Sure. We can easily compile such a list. This technique makes sense if:

(1) the lightweight implementation is much lighter than the heavyweight implementation

(2) the typical usage falls into the lightweight code path most of the time

(3) the cost of detecting the transition is not a significant cost compared to the cost of the heavyweight solution

(4) the more complex two-representation solution is necessary in order to achieve a customer-focused, realistic performance goal.

How to have a hunch when a mixed represtenation can be faster without benchmarking?

Don't. Making performance decisions based on hunches is reasoning in advance of facts. Drive performance decisions on realistic, customer focused, data-driven analysis, not on hunches. If I've learned one thing about performance analysis over the years its that my hunches are usually wrong.

Any examples?

Any number of implementations of BigInteger.

Any patterns?

Beats the heck out of me. I'm not much of one for memorizing pattern taxonomies.

Any ideas on the matter?

See above.

Perhaps you're looking for the Bridge pattern.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!