This discussion is archived
1 2 Previous Next 22 Replies Latest reply: Nov 13, 2010 11:59 AM by 796440 RSS

Factory Pattern

269490 Newbie
Currently Being Moderated
Is a factory pattern really more efficient from a runtime perspective? Is it faster to run? Does it use less memory?

If there are only a few objects that can be instantiated, then the coding can't be too difficult to maintain in one module. Say you are looking at different processing depending on if a person was male or female.

There would be some code for males and some code for females. This would be fairly easy to call in two different ways in one module.

Contrast that with instatiating the male or female object thousands of times depending on the sex of the person involved.

Wouldn't that constant instantiating have a resource cost that is greater than the benefit of slightly cleaner code or does the instantiation process work differently in the real world (both sexes modules exist in memory and are merely pointed to depending on the sex)?

Some other patterns seem to be embraced to save a few percentages of execution time but then others are embraced that use up more execution time.
  • 1. Re: Factory Pattern
    796440 Guru
    Currently Being Moderated
    ttb999 wrote:
    Is a factory pattern really more efficient from a runtime perspective? Is it faster to run? Does it use less memory?
    One does not use a pattern for "efficiency." One uses it because it is a proven, well-designed, common solution to a common problem. In some cases the Factory Pattern (by which I assume you mean Abstract Factory Pattern, or perhaps Factory Method Pattern) may execute faster or use less memory than the alternative. In other cases, the opposite may be true. But in all cases the difference will be so small that you wont' notice it, and you will not choose to use or not use that pattern, or any other, for performance reasons.

    >
    If there are only a few objects that can be instantiated, then the coding can't be too difficult to maintain in one module. Say you are looking at different processing depending on if a person was male or female.

    There would be some code for males and some code for females. This would be fairly easy to call in two different ways in one module.

    Contrast that with instatiating the male or female object thousands of times depending on the sex of the person involved.
    Instantiating a few objects vs. many has nothing to do with any Factory Pattern. Factory is only how the objects get created. You can create few or many with or without Factories.
    Wouldn't that constant instantiating have a resource cost that is greater than the benefit of slightly cleaner code
    Creating more objects uses more CPU and memory than creating fewer objects. However, you are again putting the cart before the horse. If your design calls for many objects, then create many. In particular "thousands" of instantiations is less than the blink of an eye on any modern PC. Don't fuglinate your design based on guesses at what might be faster. Use appropriate data structures and algorithms, don't prematurely optimize, and [url http://java.sun.com/developer/technicalArticles/Interviews/devinsight_1/]write dumb code.

    Don't apply a performance optimization until you've identified by measuring that the code in question is in fact a bottleneck, AND that said optimization makes a significant improvement.
  • 2. Re: Factory Pattern
    269490 Newbie
    Currently Being Moderated
    Try saying in an interview that the main thing is to get a functioning application and you can always go back and optimize and see if you get the job.
  • 3. Re: Factory Pattern
    796440 Guru
    Currently Being Moderated
    ttb999 wrote:
    Try saying in an interview that the main thing is to get a functioning application and you can always go back and optimize and see if you get the job.
    Irrelevant. The answer I gave is correct. I can't help it if your interviewer doesn't know that.

    If your interviewer is asking you to comment on the "efficiency" of a pattern, then either he doesn't know what he's talking about, or he's giving you a sneaky test.

    Additionally, that is exactly what I would say, and it's the answer I look for when I ask those sorts of questions when giving interviews. If someone were to not hire me because I gave that correct answer and he didn't realize it was correct, it's most likely not an environment I'd care to work in anyway.

    Edited by: jverd on Oct 28, 2010 11:43 AM
  • 4. Re: Factory Pattern
    jduprez Pro
    Currently Being Moderated
    Try saying in an interview that the main thing is to get a functioning application and you can always go back and optimize and see if you get the job.
    Tried it. Worked.

    Another test: if an interviewer asks you about how you base design decisions, try answering "efficiency" as your number one concern, and see if you get the job.

    Now, if the interviewer specifically asked you about the "factory pattern"'s performance characteristics, in addition to jverd's correct answer, you can point out that a factory may enable to cache objects at a later time if required.
    Indeed that's exactly the point of the pattern , and I think, of jverd's statement: once your client code uses a factory, it doesn't matter to this client code how this factory creates or elects the objects it returns, and in particular whether the factory saves memory. This helps get a working application fast.
    Now if sound profiling and performance measures do show that you have a memory consumption issue, you can make an informed decision to, e.g., cache and reuse objects, and at that point the pattern may enable to implement this reusing of cached objects without the client code having to know.

    In short, the "factory pattern" itself does not saves memory. It gives the flexibility to adapt the "creation" strategy to save memory, if it happened to be needed.

    N.B.: The "may"s and the "can"s are there as a disclaimer, as if the objects returned by the factory have state, cache and reuse are tricky, and may indeed have an impact on client code.
  • 5. Re: Factory Pattern
    796440 Guru
    Currently Being Moderated
    jduprez wrote:
    Try saying in an interview that the main thing is to get a functioning application and you can always go back and optimize and see if you get the job.
    Tried it. Worked.

    Another test: if an interviewer asks you about how you base design decisions, try answering "efficiency" as your number one concern, and see if you get the job.

    Now, if the interviewer specifically asked you about the "factory pattern"'s performance characteristics, in addition to jverd's correct answer, you can point out that a factory may enable to cache objects at a later time if required.
    Indeed that's exactly the point of the pattern,
    I wouldn't say it's exactly the point. It's certainly one potential side benefit. The main benefits of both Abstract Factory Pattern and Factory Method Pattern, as far as I understand, are abstraction and decoupling. I'd still expect them in general to actually create new objects, although there may be cases where the client doesn't care if a new object is being created, an existing but unused one being returned from a pool, or a shared in-use object.
    In short, the "factory pattern" itself does not saves memory. It gives the flexibility to adapt the "creation" strategy to save memory, if it happened to be needed.
    Yup.

    If the interviewer was specifically asking about the sharing/caching potential of Factories vs. explicit "new" operators, then CPU and memory are valid topics for discussion, with the already mentioned caveats, provisos, and disclaimers. But again, I consider that a potential side benefit, and not the central point of these patterns. The default assumption is still that objects are being created.
  • 6. Re: Factory Pattern
    jschellSomeoneStoleMyAlias Expert
    Currently Being Moderated
    ttb999 wrote:
    Some other patterns seem to be embraced to save a few percentages of execution time but then others are embraced that use up more execution time.
    Which ones? And who is claiming that?
  • 7. Re: Factory Pattern
    jschellSomeoneStoleMyAlias Expert
    Currently Being Moderated
    jduprez wrote:
    Try saying in an interview that the main thing is to get a functioning application and you can always go back and optimize and see if you get the job.
    Tried it. Worked.

    Another test: if an interviewer asks you about how you base design decisions, try answering "efficiency" as your number one concern, and see if you get the job.

    Now, if the interviewer specifically asked you about the "factory pattern"'s performance characteristics, in addition to jverd's correct answer, you can point out that a factory may enable to cache objects at a later time if required.
    I doubt that last point.

    There are patterns for pools. Which requires a mechanism for returning the object to the pool (which is not in a factory.) If you want a pool or thnk you might need a pool or decide at some point that you need one then that is what you should use.

    One can use a factory with a pool. And that is a decision that is made when considering what is needed.

    But one shouldn't try to make a factory into a pool.
    Indeed that's exactly the point of the pattern , and I think, of jverd's statement: once your client code uses a factory, it doesn't matter to this client code how this factory creates or elects the objects it returns, and in particular whether the factory saves memory. This helps get a working application fast.
    Although possible I consider it unlikely that the factory pattern is going to measurably impact the delivery time of an application.
    Now if sound profiling and performance measures do show that you have a memory consumption issue, you can make an informed decision to, e.g., cache and reuse objects, and at that point the pattern may enable to implement this reusing of cached objects without the client code having to know.

    In short, the "factory pattern" itself does not saves memory. It gives the flexibility to adapt the "creation" strategy to save memory, if it happened to be needed.
    Again no. Factory pattern has nothing to do with memory.
  • 8. Re: Factory Pattern
    jschellSomeoneStoleMyAlias Expert
    Currently Being Moderated
    jverd wrote:
    If the interviewer was specifically asking about the sharing/caching potential of Factories vs. explicit "new" operators, then CPU and memory are valid topics for discussion, ...
    I hope that isn't where an interviewer would try drive a discussion.
  • 9. Re: Factory Pattern
    796440 Guru
    Currently Being Moderated
    jschell wrote:
    jverd wrote:
    If the interviewer was specifically asking about the sharing/caching potential of Factories vs. explicit "new" operators, then CPU and memory are valid topics for discussion, ...
    I hope that isn't where an interviewer would try drive a discussion.
    Me either. It seems unrelated to the central purpose of Factories as I understand them. With the proper context though, "What do you think about this additional potential benefit of using a Factory?" is at least a more palatable question than simply, "What are the performance benefits of Factories?"
  • 10. Re: Factory Pattern
    jduprez Pro
    Currently Being Moderated
    Indeed that's exactly the point of the pattern,
    I wouldn't say it's exactly the point. It's certainly one potential side benefit.
    But you have misquoted me (admittedly, I had misworded it too): I wrote Indeed that's exactly the point of the pattern , and I think, of jverd's statement: once your client code uses a factory, it doesn't matter to this client code how this factory creates or elects the objects it returns (...)
    The main benefits of both Abstract Factory Pattern and Factory Method Pattern, as far as I understand, are abstraction and decoupling.
    What I said.
    I'd still expect them in general to actually create new objects, although there may be cases where the client doesn't care if a new object is being created, an existing but unused one being returned from a pool, or a shared in-use object.
    I don't have a copy of the GoF's book near. I would have checked if they discussed caching in Factory Method or AbstractFactory
    If the interviewer was specifically asking about the sharing/caching potential of Factories vs. explicit "new" operators, then CPU and memory are valid topics for discussion, with the already mentioned caveats, provisos, and disclaimers. But again, I consider that a potential side benefit, and not the central point of these patterns.
    Yes.
    The default assumption is still that objects are being created.
    I disagree (but as noted, the GoF book may have discussed it). As I wrote (awkwardly), and as you pointed out, the point of both patterns is to decouple the client code from the factory's implementation. Assuming anything about the implementation is somewhat contradictory. Unless the contract for the factory method (the method, not the pattern) makes that explicit.
    I remember an old topic on the Sun forums where "factory method naming conventions" were discussed; I pointed out that naming a method createXyz() or newXyzInstance() suggested that a new instance would be returned, whereas a more neutral getXyz() gave more liberty.
  • 11. Re: Factory Pattern
    jschellSomeoneStoleMyAlias Expert
    Currently Being Moderated
    jduprez wrote:
    The default assumption is still that objects are being created.
    I disagree (but as noted, the GoF book may have discussed it). As I wrote (awkwardly), and as you pointed out, the point of both patterns is to decouple the client code from the factory's implementation. Assuming anything about the implementation is somewhat contradictory. Unless the contract for the factory method (the method, not the pattern) makes that explicit.
    I remember an old topic on the Sun forums where "factory method naming conventions" were discussed; I pointed out that naming a method createXyz() or newXyzInstance() suggested that a new instance would be returned, whereas a more neutral getXyz() gave more liberty.
    Except that is exactly the point of the Factory pattern. To create objects. Nothing else

    Following is description of Factory pattern from GoF.

    +"Define an interface from creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subsclasses."+

    Following is from Flyweight.

    +"Use sharing to support large numbers of fine-grained objects efficiently"+

    And I am not suggesting that flyweight is equivalent to the pool patterns but rather that other patterns specifically mention efficiency/sharing while Factory does not. Because that isn't what Factory does.
  • 12. Re: Factory Pattern
    jduprez Pro
    Currently Being Moderated
    jschell wrote:
    jduprez wrote:
    (...) in addition to jverd's correct answer, you can point out that a factory may enable to cache objects at a later time if required.
    I doubt that last point.

    There are patterns for pools. Which requires a mechanism for returning the object to the pool (which is not in a factory.)
    I didn't try to analyze fully which kind of "caching" and under which circumstances such caching can be implemented by a factory (I lazily added conservative provisions instead). But it seems a pool of stateless objects doesn't need a return-to-pool method (admittedly, such objects are not very useful).
    If you want a pool or thnk you might need a pool or decide at some point that you need one then that is what you should use.
    One can use a factory with a pool. And that is a decision that is made when considering what is needed.
    But one shouldn't try to make a factory into a pool.
    Well, isn't javax.sql.DataSource a counter-example? Quoting the javadoc:
    A factory for connections to the physical data source that this DataSource object represents. (...)
    There are three types of implementations:

    1. Basic implementation -- produces a standard Connection object
    2. Connection pooling implementation -- produces a Connection object that will automatically participate in connection pooling. This implementation works with a middle-tier connection pooling manager.
    (...)
    Indeed that's exactly the point of the pattern , and I think, of jverd's statement: once your client code uses a factory, it doesn't matter to this client code how this factory creates or elects the objects it returns, and in particular whether the factory saves memory. This helps get a working application fast.
    Although possible I consider it unlikely that the factory pattern is going to measurably impact the delivery time of an application.
    You're right, I did not put enough effort into writing properly, and that last sentence is stupid as such (at least you quoted the first part correctly :o).
    I meant that not caring (yet) about the peformance does help to get a working prototype faster. Performance can be improved (where needed) from that early point. And having placed decoupling patterns (where deemed appropriate, such as, where analysis points out likely variability, uncertainty, or risk) in the early design helps doing these improvements with limited impact on the client code.
    Admittedly, that's not specific to performance issues or improvements, any kind of improvement benefits from this flexibility.

    Note the conservative provision "where deemed appropriate", as it is well known too that unneeded flexibility negatively impacts the cost and delivery time of an application.
    In short, the "factory pattern" itself does not saves memory. It gives the flexibility to adapt the "creation" strategy to save memory, if it happened to be needed.
    Again no. Factory pattern has nothing to do with memory
    Factory patterns have to do with flexibility and decoupling. They don't constrain what kind of reasons can leverage this flexibility. If it's memory management strategy that benefits from it, so be it.
  • 13. Re: Factory Pattern
    jduprez Pro
    Currently Being Moderated
    Except that is exactly the point of the Factory pattern. To create objects. Nothing else
    Following is description of Factory pattern from GoF.
    +"Define an interface from creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subsclasses."+
    Err, you do have a point...
    Are you sure though, that the "Discussion" section doesn't mention caching and reusing?

    Here is another quote, from Craig Larman's "Applying UML and Patterns":
    Factory objects have several advantages:
    - Separate the responsibility of complex creation into cohesive helper objects
    - Hide potentially complex creatin logic
    - Allow introduction of performance-enhancing memory management strategies, such as object caching or recycling
  • 14. Re: Factory Pattern
    jschellSomeoneStoleMyAlias Expert
    Currently Being Moderated
    jduprez wrote:
    Well, isn't javax.sql.DataSource a counter-example? Quoting the javadoc:
    A factory for connections to the physical data source that this DataSource object represents. (...)
    There are three types of implementations:

    1. Basic implementation -- produces a standard Connection object
    2. Connection pooling implementation -- produces a Connection object that will automatically participate in connection pooling. This implementation works with a middle-tier connection pooling manager.
    (...)
    I don't consider the Java API as an authoratative source of anything except describing how the API works. And it doesn't always get that right either.
1 2 Previous Next

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points